简体   繁体   English

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

[英]How get elements which are between two of the same selector class

I need get elements which are between two of the same css selector class.我需要获取位于两个相同 css 选择器类之间的元素。

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

Will you only ever be dealing with two, identical classes on a page?您会在一个页面上只处理两个相同的类吗? If so, then (in the very specific example given) you could use something along the lines of:如果是这样,那么(在给出的非常具体的示例中)您可以使用以下内容:

 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>

Edit Slight tweak to above code based on additional information.编辑根据附加信息对上述代码进行轻微调整。

You can add a custom class, or update the style via the JavaScript DOM API.您可以添加自定义类,或通过 JavaScript DOM API 更新样式。

Let me suggest to you a direct solution for this -让我向您建议一个直接的解决方案 -

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)
    }
})

then you have all active divs and you can do whatever with divs between this two (or other) from the array above ...那么你就有了所有活动的 div,你可以对上面数组中的这两个(或其他)之间的 div 做任何事情......

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

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

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