Vialito
Vialito

Reputation: 523

How to remove a classname from an element's classlist by index?

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.

Upvotes: 1

Views: 1536

Answers (1)

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

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);

Upvotes: 3

Related Questions