如何检查两个DOM元素是否是兄弟姐妹?
<div>
<a></a>
<b></b>
<p></p>
</div>
<i></i>
测试<b>
是<a>
的兄弟,而不是<i>
的兄弟
答案 0 :(得分:9)
var a = $('a'),
b = $('b'),
i = $('i');
a.siblings().is(b); // true (since "b" is sibling of "a")
a.siblings().is(i); // false (since "i" is sibling of "div" and not of "a")
a.siblings().is(a); // false (can't be singling of itself)
var elm_p = document.querySelector('p');
var elm_a = document.querySelector('a');
var elm_i = document.querySelector('i');
// - iterate all the siblings of elm1 and check if any is elm2.
// - make sure elm1 is a different node than elm2
// - rely on ES2015 destructuring & Array.some
function checkElementsAreSiblings(elm1, elm2){
return elm1 != elm2 && [...elm1.parentNode.children].some(child => child == elm2)
}
console.log(
checkElementsAreSiblings(elm_p, elm_a), // true
checkElementsAreSiblings(elm_a, elm_p), // true
checkElementsAreSiblings(elm_a, elm_a), // false
checkElementsAreSiblings(elm_a, elm_i) // false
)
&#13;
<div>
<a></a>
<b></b>
<p></p>
</div>
<i></i>
&#13;