Reputation: 133
I need get elements which are between two of the same css selector class.
<div>
<div></div>
<div class='active'></div>
<div></div> // need this
<div></div> // need this
<div class='active'></div>
</div>
Upvotes: 0
Views: 63
Reputation: 126
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.
Upvotes: 2
Reputation: 300
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 ...
for (let i = activeIndexes[0] + 1; i < activeIndexes[1]; i++){
//todo actions
console.log(divs[i])
}
Upvotes: 0