检查元素(DOM节点)是否是兄弟节点

时间:2016-05-17 13:19:29

标签: javascript jquery dom

如何检查两个DOM元素是否是兄弟姐妹?

示例DOM结构:

<div>
    <a></a>
    <b></b>
    <p></p>
</div>
<i></i>

测试<b><a>的兄弟,而不是<i>的兄弟

1 个答案:

答案 0 :(得分:9)

jQuery的:

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)

香草:

&#13;
&#13;
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;
&#13;
&#13;