html - How to get css selector for an element using javascript? - Stack Overflow

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

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

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

Share Improve this question edited May 23, 2017 at 12:09 CommunityBot 11 silver badge asked Mar 2, 2015 at 6:57 optimus primeoptimus prime 771 silver badge3 bronze badges 5
  • What selector you want to get? Please try to provide more info. – pavel Commented Mar 2, 2015 at 7:00
  • “to get the unique selector of an element” – there is no such thing. Elements can be selected in a multitude of different ways. – C3roe Commented Mar 2, 2015 at 8:14
  • 1 Are you looking for a selector that uniquely selects a particular element, as opposed to a unique selector for an element? – Mårten Wikström Commented Mar 2, 2015 at 8:27
  • 1 @MårtenWikström Yes, like developer tools "Copy CSS Path". – optimus prime Commented Mar 2, 2015 at 10:31
  • @optimusprime: Then it's more clear what you're asking for. I've edited your question. Please provide links to the answers on StackOverflow that did not answer your question. – Mårten Wikström Commented Mar 2, 2015 at 11:03
Add a ment  | 

3 Answers 3

Reset to default 2

Just found this post, had a look at the only answer and got terrified by it's plexity 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.

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

http://jsfiddle/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 

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'>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745122220a4612480.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信