检查元素(DOM节点)的兄弟姐妹

问题描述 投票:3回答:1

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

Example DOM structure:

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

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

javascript jquery dom
1个回答
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)

香草:

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
)
<div>
    <a></a>
    <b></b>
    <p></p>
</div>
<i></i>
© www.soinside.com 2019 - 2024. All rights reserved.