I'm creating a group of <div>
's that have separate content:
<div >
<div ></div>
<div ></div>
<div ></div>
</div>
I need to be able to get the specific index value of a <div>
when it has a certain class applied to (e.g., myClass
)
const item = document.querySelector(".container__item");
const items = document.querySelectorAll(".container__item");
const myClass = document.querySelector(".myClass");
I'm looping through the collection of items but not able to get the index value, e.g., 0, 1, 2
. FYI, I'll be converting those values to 1, 2, 3
.
for (var i = 0; i < item.length; i ) {
var hasClass = item[i]classList.contains(showItem);
if (hasClass) {
console.log(i);
}
}
CodePudding user response:
You can use map and subsequently filter the element list:
const myClassElementsWithIndexes =
[...document.querySelectorAll(`.container .container__item`)]
.map( (item, i) => ({elem: item, index: i}) )
.filter(item => item.elem.classList.contains(`myClass`) );
console.log(myClassElementsWithIndexes);
<div >
<div ></div>
<div ></div>
<div ></div>
</div>
CodePudding user response:
You're iterating over item
instead of items
in your for loop. I added some ID's just for debugging to show you. You're also missing a period after the index [i] before accessing classList.
let items = document.querySelectorAll(".container__item");
for ( var i = 0; i < items.length; i ) {
console.log( items[i].id );
var hasClass = items[i].classList.contains('myClass');
if (hasClass) {
console.log('Index: ' i);
}
}
<div >
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
</div>
CodePudding user response:
You can select the element with the container
class and loop over all its children and then grab the index of those children where the className
includes myClass
.
const container = document.querySelector(".container");
Array.from(container.children).forEach((c, i) => {
if (c.className.includes("myClass")) {
console.log(i 1);
}
});
<div >
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
You can also do it using Element.classList, as shown below:
const container = document.querySelector(".container");
Array.from(container.children).forEach((c, i) => {
if (c.classList.contains("myClass")) {
console.log(i 1);
}
});
<div >
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>