1

There's this situation in which you don't know a classname's value beforehand. You do know that the classname is, for example, the 3rd class of an html element.

If you know the classname's index in the classlist, but you don't know its exact value, then how to remove it?

I'd guessed something like this would work:

var elements = document.querySelector('.element');

for (var i = 0; i < elements.length; i++) {

  var classes = elements[i].classList;

  for (var j = 0; j < classes.length; j++) {

    if (classes[2] !== null) {

      elements[i].classList.delete(elements[i].classList[2])
      elements[i].classList.add('classname')

    }
  }
}

How can you delete a classname by index of the classlist? And how to replace or toggle the value of the classname with this same index?

The effort a Jquery answer would be appreciated, but most of my curiosity goes out to a vanilla Javascript solution.

Vialito
  • 523
  • 7
  • 28
  • 2
    Relying on ordering of class names is an **extremely** bad idea. – Pointy Oct 09 '19 at 19:01
  • @Pointy I don't see another way. Plus the classname will defenitly always be at the same position. – Vialito Oct 09 '19 at 19:03
  • Possible duplicate of [How to change an element's class with JavaScript?](https://stackoverflow.com/questions/195951/how-to-change-an-elements-class-with-javascript) – fnostro Oct 09 '19 at 19:04
  • 2
    No it will not "definitely" be at the same position; browsers are free to arbitrarily re-arrange the set of classes in any order they want. Something is fundamentally wrong with what you're trying to do. – Pointy Oct 09 '19 at 19:04
  • 1
    I can't see a use-case for this. Can you explain *why* you would want to remove a className by index? (Perhaps its an XY problem.) – Moob Oct 09 '19 at 19:07
  • @Moob A user adds content displayed in blocks from a cms. Depending on the viewport 1, 2 or three blocks are rendered next to each other in each row. Each block contains a list with a more button. The user want to expand the entire row of blocks by clicking on only one of the more buttons. So that is all the lists need to expand in all the 1, 2, or 3 blocks shown next to each other in this row. I gave each row a class. The classes then change on resize. So I don't know the classnames in advance. Any ideas? – Vialito Oct 10 '19 at 04:52

1 Answers1

3

The following code should work. Assuming domElement is the element and index is the index to remove the class

But I must say the browsers(or some user extensions) may change the classList order and it is generally not a very good idea.

var domElement = document.querySelector('.element');
let classToDelete = Array.from(domElement.classList)[index];
domElement.classList.remove(classToDelete);
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25