简体   繁体   中英

How to get css selector for an element using javascript?

Is there any jQuery plugin or javascript code that returns a CSS-selector that uniquely selects a particular element?

I'm looking for something with similar functionality as provided by the Copy CSS Path function in Chrome's developer tools, giving me a selector that looks something like this:

#question > table > tbody > tr:nth-child(2) > td > div > h2

Answers I tried

Get unique selector of element in Jquery

Get unique selector jQuery

Not perfect, but written fast (for You) : )

http://jsfiddle.net/k1qs69fz/7/

Code:

function getCSSPath(el, callback){

    var fullPath = '';

    var cssPathFn = function (el, callback){

        var elPath = '';

        elPath = $(el).prop('tagName').toLowerCase();

        if(typeof $(el).attr('id') !== 'undefined'){

            elPath = elPath+'#'+$(el).attr('id');
        }

        if(typeof $(el).attr('class') !== 'undefined'){

            elPath = elPath+'.'+$(el).attr('class').split(' ').join('.');
        }

        fullPath = elPath+' '+fullPath;

        if(typeof $(el).parent().prop('tagName') !== 'undefined'){

            cssPathFn($(el).parent(), callback);
        }
        else{

            callback(fullPath);
        }
    };

    cssPathFn(el, callback);
}


Usage:

getCSSPath($('selector'), callbackFunction);

Function is based on tag name, id and class names, indexes are not supported.


Sample usage (for HTML code on JSFiddle):

$(document).ready(function (){

    getCSSPath($('#lorem-ipsum'), function (path){

        console.log(path);
    });
});


Sample Result:

html body div#id1.c1.c2.c3 div#id2 div.c4.c5 span span.c6 ul li a span#lorem-ipsum 

Just found this post, had a look at the only answer and got terrified by it's complexity and by bizarre denial from using jQuery functions. Sorry for criticism, but i really i got stunned by this callback system. Here, have it in easy to use form:

function getCSSPath(el) {
    let rendered_path_parts = [];

    $( el ).parents().addBack().each((i, el) => {
        const $el = $( el );
        let current_el_path = $el.prop('tagName').toLowerCase();

        if ($el.attr('id')) {
            current_el_path += '#' + $el.attr('id');
        }

        if ($el.attr('class')) {
            current_el_path += '.' + $el.attr('class').split(' ').join('.');
        }

        rendered_path_parts.push( current_el_path );
    })

    return rendered_path_parts.join(' ');
}

$.fn.extend({
    getPath: function() {
        return getCSSPath(this.length === 1 ? this : this.eq(0));
    }
});

getCSSPath(some_element);
some_jquery_element.getPath();

Note that rendered selector will not include element' index, so it is less descriptive than selector developer tools can make for you.

Here is a pure JavaScript implementation of what the others had using Element.attributes so it should work everywhere.

I made it a snippet so you can see that document.querySelector works with the selector found.

 function getCSSSelector(el){ let selector = el.tagName.toLowerCase(); const attrs = el.attributes for (var i = 0; i < attrs.length; i++) { let attr = attrs.item(i) if (attr.name === 'id') selector += `#${attr.value}`; if (attr.name === 'class') selector += attr.value.split(' ').map((c) => `.${c}`).join(''); if (attr.name === 'name') selector += `[${attr.name}=${attr.value}]`; } return selector } let el = document.querySelector('input#id.abc'); let selector = getCSSSelector(el); console.log(selector) document.querySelector(selector).value = selector;
 <input id="id", class="abc def" name='name' style='width: 200px'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM