簡體   English   中英

如何從給定的DOM對象中獲取完整的css選擇器字符串

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

我想寫一個函數

function f (domEl){
    //some code here

    //returns a string
}

這樣:

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

應該總是返回true(當然,無論domEl是什么層次結構):

舉個例子,讓我們說:

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

而且,我想選擇粗體li元素。 我得到那個元素並將其傳遞給我的函數f。

演示: 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);

選擇器看起來像這樣(對於我在示例中使用的代碼) ...

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM