Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why wont my onclick not remove any of my classes?

I have a huge problem here.
I can't get my onclick to work as I want .. So I hope someone here can help me.

<a href="#" onclick="document.getElementsByClassName('nice').style.display='none';" class="sorter">#NiceToKnow</a>

<div id="cards" class="nice"></div>
<div id="cards" class="nice"></div>
<div id="cards" class="nice"></div>
<div id="cards" class="video"></div>

I want it to display: none; every of my class="nice", so you only can see class="video", but nothing happens at all.

like image 861
Morten Buller Resen Kibsgaard Avatar asked Mar 15 '23 08:03

Morten Buller Resen Kibsgaard


1 Answers

You are selecting the elements of the class not the class itself. So you will have to loop through the elements as javascript can only edit what is in the DOM not the CSS classes that effect your elements. So getElementsByClassName returns an array of nodes in which we must loop through and hide each one. Click runsnippet below to see this work

function changeNice(){
//ASSIGN ELEMENTS TO ARRAY
elementsofClass=document.getElementsByClassName('nice');
for(i=0; i<elementsofClass.length; i++){
    //HIDE SELECTED ELEMENT
    elementsofClass[i].style.display='none';
  
  
}}
<a href="#" onclick="changeNice();" class="sorter">#NiceToKnow</a>

<div id="cards1" class="nice">TEST 1</div>
<div id="cards2" class="nice">TEST 2</div>
<div id="cards3" class="nice">TEST 3</div>
<div id="cards4" class="video">I don't HIDE</div>

Also don't use duplicate ID. This will cause errors later when trying to select your elements.

like image 91
PC3TJ Avatar answered Mar 23 '23 22:03

PC3TJ