繁体   English   中英

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

[英]Check if elements (DOM Nodes) are siblings

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

DOM 结构示例:

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

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

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 areSiblings(elm1, elm2){ return elm1 != elm2 && [...elm1.parentNode.children].some(child => child == elm2) } // tests [ [elm_p, elm_a], // true [elm_a, elm_p], // true [elm_a, elm_a], // false [elm_a, elm_i] // false ].forEach(([a,b]) => console.log(areSiblings(a,b)))
 <div> <a></a> <b></b> <p></p> </div> <i></i>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM