Removing class elements

Hi,

I am trying to remove a series of class elements from a page (.whatever in the example), and I would much appreciate if someone explain to me why this script works:

if (window.matchMedia("(min-width: 400px)").matches) {
  var elements = document.getElementsByClassName('whatever');
  for(var i=0; i<elements.length; i++) { 
    elements[i].style.display='none';
  }
}

…and this one does not work at all:

if (window.matchMedia("(min-width: 400px)").matches) {
  var elements = document.getElementsByClassName('whatever');
  for(var i=0; i<elements.length; i++) { 
    elements[i].remove();
  }
}

Thanks very much

Because .getElementsByClassName() returns a live list, so when you remove an element from the DOM, that list gets actually shifted and your skipping every other element. Compare this to .querySelectorAll(), which does not return a live list; the elements will stay in the list even after removal and the loop will run as expected:

var elements = document.querySelectorAll('.whatever')
var i

for (i = 0; i < elements.length; i++) { 
  elements[i].remove()
}

Hi there andresb,

I you need to use javascript for this, then
you are most probably doing something. :rolleyes:

Why are you not using CSS? :eek:

coothead

The second example doesn’t work because the list of elements updates live. When for example the first element is removed, the elements list updates and what was the second element becomes the first.

One solution to this is to instead loop backwards through the elements.
Another solution that I prefer though, is to use a while loop instead.

while (elements.length > 0) {
    elements[0].remove();
}

Why use javascript when it can be done like this…

@media  ( min-width: 25em ) {
.whatever {
    display: none;
  }
 }

coothead

3 Likes

Yes, I understand. It works.

Thanks.

Because css does not remove the elements from the code.

JavaScript does not remove the code either. :rolleyes:
Open your HTML file and cast your optics over the code. :rofl:

coothead

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.