Getting Element Path for selector

前端 未结 4 911
既然无缘
既然无缘 2020-12-16 04:59

Running into a spot of trouble and basically trying to create a variable which can be used as a selector. eg

$(\'a\').click(function(){
   var selector = $(t         


        
4条回答
  •  遥遥无期
    2020-12-16 05:30

    Perhaps something like this:

    function dompath( element )
    {
        var path = '';
        for ( ; element && element.nodeType == 1; element = element.parentNode )
        {
            var inner = $(element).children().length == 0 ? $(element).text() : '';
            var eleSelector = element.tagName.toLowerCase() + 
               ((inner.length > 0) ? ':contains(\'' + inner + '\')' : '');
            path = ' ' + eleSelector + path;
        }
        return path;
    }
    

    This modified a method from another question to go through, and add in the full text contents of the tag via a :contains() operator only if the tag has no children tags.

    I had tested with this method:

    $(document).ready(function(){
        $('#p').click(function() {
          console.log(dompath(this));
        });
    });
    

    Against this:

    
        
            
    • hi
    • hello world

    The results of clicking on p then get output as:

    html body div ul li:contains('hi')

提交回复
热议问题