这是我试图查询的标记。因此给出标记:
<table class="non-unique-identifier table">
<tr><td><div id="unique-identifier"></div></td></tr>
</table>
我正在查询#unique-identifier:
var myDiv = document.getElementById('#unique-identifier');
然后我尝试选择表格。问题是我想让代码不脆弱,所以我不需要这样做:
var myDiv = document.getElementById('#unique-identifier'),
myTable = myDiv.parentNode.parentNode.parentNode.parentNode;
我的问题
目前是否有相当于 $().closest() 的 DOM 实现?首选最接近且高效且无需嵌套 for 循环的实现。
局限性
我被要求不使用 jQuery 或 sizzle 来解决这个特定问题或引入任何新的库。该代码也很旧。因此,这就是这种限制和存在的原因<tables>
.
如果没有循环,你就无法做到这一点:
function closest (el, predicate) {
do if (predicate(el)) return el;
while (el = el && el.parentNode);
}
好吧,实际上你可以使用递归(伪装的循环):
function closest(el, predicate) {
return predicate(el) ? el : (
el && closest(el.parentNode, predicate)
);
}
演示(使用Sizzle https://sizzlejs.com/对于 DOM 查询):
// s = selectors
// n = number of selectors
// get closest s[i+1] from s[i]
// where 0 <= i < n and i % 2 = 0
function main (s) {
var i, el, from;
var n = s.length;
for (i = 0; i < n; i += 2) {
from = Sizzle(s[i])[0];
el = closest(from, function (el) {
return !!el && el !== document && (
Sizzle.matchesSelector(el, s[i + 1])
);
});
console.log(el);
}
}
function closest (el, predicate) {
do if (predicate(el)) return el;
while (el = el && el.parentNode);
}
main([
"#winner" , "b",
"#winner" , "p",
"#winner" , "div",
"#winner" , "div:not(#trump)",
"#winner" , "#clinton",
"#looser" , "html"
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/sizzle/1.10.18/sizzle.min.js"></script>
<div id="main">
<div id="trump">
<p>Donald <b id="winner">Trump</b></p>
</div>
<div id="clinton">
<p>Hillary <b>Clinton</b></p>
</div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)