Get the DOM path of the clicked

后端 未结 8 1451
刺人心
刺人心 2020-11-30 06:01

HTML




         


        
8条回答
  •  悲&欢浪女
    2020-11-30 06:25

    Here is a solution for exact matching of an element.

    It is important to understand that the selector (it is not a real one) that the chrome tools show do not uniquely identify an element in the DOM. (for example it will not distinguish between a list of consecutive span elements. there is no positioning/indexing info)

    An adaptation from a similar (about xpath) answer

    $.fn.fullSelector = function () {
        var path = this.parents().addBack();
        var quickCss = path.get().map(function (item) {
            var self = $(item),
                id = item.id ? '#' + item.id : '',
                clss = item.classList.length ? item.classList.toString().split(' ').map(function (c) {
                    return '.' + c;
                }).join('') : '',
                name = item.nodeName.toLowerCase(),
                index = self.siblings(name).length ? ':nth-child(' + (self.index() + 1) + ')' : '';
    
            if (name === 'html' || name === 'body') {
                return name;
            }
            return name + index + id + clss;
    
        }).join(' > ');
    
        return quickCss;
    };
    

    And you can use it like this

    console.log( $('some-selector').fullSelector() );
    

    Demo at http://jsfiddle.net/gaby/zhnr198y/

提交回复
热议问题