简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM