2

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

Community
  • 1
  • 1
optimus prime
  • 77
  • 1
  • 3

3 Answers3

2

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.

lucifer63
  • 784
  • 9
  • 32
1

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 
Mateusz Mania
  • 839
  • 4
  • 15
1

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'>
mvndaai
  • 3,453
  • 3
  • 30
  • 34
  • I tried to use this function on kijiji.ca for removing an annoying element, the function should return "div.sc-58853b75-0.ofGHb" but instead it return this: "div.sc-58853b75-0.jOwRwk". That's weird because I can't even find the "jOwRwk" class anywhere in the source. Do you have any clue about what could be the problem here? – Frank Einstein Aug 25 '23 at 21:17
  • I used this function on other elements and it worked perfectly... I really don't know why it's doing this on this element specifically... – Frank Einstein Aug 25 '23 at 21:23