如何获取位于同一选择器类的两个之间的元素



我需要获取位于同一css选择器类的两个之间的元素。

<div>
<div></div>
<div class='active'></div>
<div></div> // need this
<div></div> // need this
<div class='active'></div>
</div>

您会在一个页面上只处理两个相同的类吗?如果是这样的话,那么(在给出的非常具体的例子中(你可以使用如下的东西:

var el = document.querySelector(".active").nextElementSibling;
while ( !( el.classList.contains( "active" ) ) ) {
// opt 1 - add a class that can be used to add style
el.classList.add("custom-class");

// opt 2 - use the JS DOM API to directly update element styles
el.style.color = "yellow";

// go to the next element in the DOM
el = el.nextElementSibling;

};
/* Demo style */
.custom-class{
background: pink;
height: 50px;
width: 50px;
}
<div>
<div></div>
<div class='active'></div>
<div>// need this</div> 
<div>// need this</div> 
<div class='active'></div>
</div>

编辑根据其他信息对上述代码进行轻微调整。

您可以添加自定义类,或者通过JavaScriptDOMneneneba API更新样式。

让我向您建议一个直接的解决方案-

let activeIndexes = []
let divs = $($('.active')[0]).parent().find('div') // this will return you an ordered array of divs ( or you can modify a selector to get whatever block you want)
divs.each(function(index, element){
if ($(element).hasClass('active')) {
activeIndexes.push(index)
}
})

那么您就有了所有活动的div,您可以从上面的数组中对这两个(或其他(之间的div执行任何操作。。。

for (let i = activeIndexes[0] + 1; i < activeIndexes[1]; i++){
//todo actions
console.log(divs[i])
}

最新更新