Change all classes for an element (HTML + Javascript)

This code search for all the elements of a certain class and replaces its classes for a new one.

Code:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    var elements = document.querySelectorAll(".oldClass");

    for(var i = 0; i < Object.keys(elements).length; i++)
    {
      elements[i].className = "newClass";
    }
  }, false);
</script>

 

This code search for a single element of a certain ID and replaces its classes for a new one.

Code:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("MyElementID").className = "newClass";
  }, false);
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *