hrishikeshp19
hrishikeshp19

Reputation: 9036

how to get a complete css selectors string from a given DOM object

I want to write a function

function f (domEl){
    //some code here

    //returns a string
}

such that:

$(f(domEl))[0] == domEl

should always return true (of course, regardless at what hierarchy domEl is):

As an example, Let's say:

HTML
    body
        ul
            li
            **li**
            li
                ul
                    li

and, I want to select bold li element. I get that element and pass that into my function f.

Upvotes: 1

Views: 326

Answers (1)

user1106925
user1106925

Reputation:

DEMO: http://jsfiddle.net/vzWgb/

function f (domEl){
    var s = [],
        node = domEl;

    do {
        s.unshift(build_nth_selector(node));
    } while((node = node.parentNode) && node !== document.body)

    s.unshift('BODY')

    return s.join(' > ');
}

function build_nth_selector(node) {
    var p = 1,
        n_name = node.nodeName.toUpperCase();
    while (node = node.previousElementSibling)
        ++p;
    return n_name + ':nth-child(' + p + ')'
}

var $ = function(s) { return document.querySelector(s); };

var el = document.getElementById('target');

alert(f(el));

alert($(f(el)) === el);

The selector looks like this (for the code I used in the example)...

BODY > DIV:nth-child(1) > DIV:nth-child(1) > UL:nth-child(1) > LI:nth-child(2) > UL:nth-child(1) > LI:nth-child(5)

Upvotes: 4

Related Questions