如何查找当前所选DOM对象的所有同级对象 [英] How to find all Siblings of the currently selected DOM object
问题描述
在JavaScript中查找所有nextSiblings和previousSiblings的完美方法是什么。我尝试了几种方法,但没有获得准确的解决方案。如果选择了任何元素,我需要获取除空格,任何空格或换行符以外的所有下一个同级的长度。
What is the perfect way to find all nextSiblings and previousSiblings in JavaScript. I tried few ways but not getting accurate solution. If any element is selected, I need to get length of all next siblings excluding white-space, any spaces or line-breaks.
我也不想使用jQuery为此。我专门从JavaScript中查找内容
Also I don't want to use jQuery for this. I am specifically looking something from JavaScript
推荐答案
我假设这发生在事件处理程序中,其中 this
是对要影响其同级的目标元素的引用。
I'll assume that this takes place inside an event handler where this
is a reference to the targeted element whose siblings you want to affect.
如果没有,则需要进行调整。
If not, adjustments will be needed.
var result = [],
node = this.parentNode.firstChild;
while ( node ) {
if ( node !== this && node.nodeType === Node.ELEMENT_NODE )
result.push( node );
node = node.nextElementSibling || node.nextSibling;
}
// result will contain all type 1 siblings of "this"
这篇关于如何查找当前所选DOM对象的所有同级对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!