Search code examples
javascripthtmlmaterialize

How do i change one of the classes in an element with Javascript


If i have the library materialize and an element "h1", how do i change only its background color "black" to "white" using javascript? For example using a button.

<h1 class="black red-text">Test</h1>

Solution

  • Create a function and a white class. Inside the function use document.getElementsByClassName . Since document.getElementsByClassName is a collection so you need to use index like [0] to access it

    function changeColor() {
      document.getElementsByClassName("black")[0].classList.add('white')
    
    }
    .white {
      background: white !important;
    }
    
    .black {
      background: black;
    }
    
    .red-text {
      color: red;
    }
    <h1 class="black red-text">Test</h1>
    <button onclick='changeColor()'>Change Color</button>