我想写一个函数
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。
答案 0 :(得分:4)
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);
选择器看起来像这个(对于我在示例中使用的代码) ......
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)