Ogechi Chibueze
Ogechi Chibueze

Reputation: 53

I can't add or remove a class

I am trying to remove a class and add a class within one function. But when I click on the button nothing is happening.

This is my code

function unlikeVerhaal(unlike) {
  unlike.preventDefault;
  document.querySelector('#unliked').classList.add('onzichtbaar');
  document.querySelector('#liked').classList.remove('onzichtbaar');
}

document.querySelector('.likebutton').addEventListener('submit', unlikeVerhaal);
.onzichtbaar {
  display: none;
}
<li>
  <button type="submit" class="likebutton">
    <img src="icons/lined.png" alt="lined heart" class="unliked" id="unliked">
    <img src="icons/solid.png" alt="solid heart" id="liked" class="onzichtbaar">
  </button> 777
</li>

What I am trying to get is that the class is added to the first image and removed by the second image.

Upvotes: 3

Views: 166

Answers (2)

20yco
20yco

Reputation: 906

This will works as you expect:

function unlikeVerhaal(e) {
    e.preventDefault;
    document.getElementById('unliked').classList.add('onzichtbaar');
    document.getElementById('liked').classList.remove('onzichtbaar'); 
} 

document.getElementById('likebutton').addEventListener('click', unlikeVerhaal);

Just change submit to click and remove type from button

Fiddle

Update:

Updated fiddle

Upvotes: -1

AndrewL64
AndrewL64

Reputation: 16311

You just need to use a combination of the three methods .contains(), .add() and .remove() from the element.classList property along with a simple if/else statement (or a ternary operator if you prefer that) as can be seen in the Code Snippet below:

var btn = document.querySelector('.likebutton');

function unlikeVerhaal() {
    var ul = document.getElementById("unliked");
    var l = document.getElementById("liked");
    
    if (ul.classList.contains("onzichtbaar")) {
        ul.classList.remove("onzichtbaar");
        l.classList.add("onzichtbaar");
        console.log("Inspect your elements to see the class switching!")
    } else {
        l.classList.remove("onzichtbaar");
        ul.classList.add("onzichtbaar");
        console.log("Inspect your elements to see the class switching!")
    }
}

btn.addEventListener("click", unlikeVerhaal)
.onzichtbaar {background-color: green;}
<li>
      <button type="button" class="likebutton">
      <div class="unliked" id="unliked">A</div>
      <div id="liked" class="onzichtbaar">B</div>
      </button> 777
</li>


You can either inspect the elements to see the class switching between the two or you can just watch the green background styling which is applied to an element with the onzichtbaar class name switching between the two.

Upvotes: 3

Related Questions