Skip to content Skip to sidebar Skip to footer

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 provid

Solution 1:

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:

functiongetCSSPath(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() {
        returngetCSSPath(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.

Solution 2:

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

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

functiongetCSSPath(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:

htmlbodydiv#id1.c1.c2.c3div#id2div.c4.c5spanspan.c6ulliaspan#lorem-ipsum

Solution 3:

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.

functiongetCSSSelector(el){
    let selector = el.tagName.toLowerCase();
    const attrs = el.attributesfor (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;
<inputid="id", class="abc def"name='name'style='width: 200px'>

Post a Comment for "How To Get Css Selector For An Element Using Javascript?"