user3733479 user3733479 - 6 months ago 23
Javascript Question

Javascript get elements by multiple class names

I wrote a function to remove all the elements with a certain class. I tried to make the function so that I can input multiple classes, divided by '|' sings.

Somehow it is nog working correctly, some elements are deletet, some ar not...
Can somebody tell me what ik am doing wrong?



function removeElement(classNames){

var classNamesArray = classNames.split("|");

for (var i = 0; i < classNamesArray.length; i++) {
alert(classNamesArray[i]);
var elements = document.getElementsByClassName(classNamesArray[i])
for (var j = 0; j < elements.length; j++){
alert(elements[j]);
elements[j].remove();
}
}
}

<div class="admin">test div1</div>
<div class="admin">test div2</div>
<div class="normal">test div3</div>
<div class="admin">test div4</div>
<span class="admin">test span1</span>
<div class="admin normal">test div1</div>
<div class="admin">test div2</div>
<div class="normal">test div3</div>
<div class="admin">test div4</div>
<span class="admin">test span1</span>

<br>

<button onClick="removeElement('admin|normal')">do it now!</button>




Answer

When you are removing an element you are forgetting that the array of elements is getting shorter.

change your second FOR loop to run from the end of the array like this:

for (var j = elements.length; j > 0; j--){
Comments