Why is my onclick not deleting any of my classes?

I have a huge problem here.
I can't get my onclick to work the way 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 displayed: none; each of my class = "good", so you can only see class = "video", but nothing happens at all.

+4
source share
6 answers

, . , , javascript , DOM, CSS, . getElementsByClassName , . , .

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>
Hide result

ID. .

+5

getElementsByClassName , .

. . .

window.hideAllniceClass = function () {
    var elems = document.getElementsByClassName('nice');
    for (var i = 0; i != elems.length; ++i) {
        elems[i].style.display = "none"; // hidden has to be a string
    }
}
<a href="#" onclick="hideAllniceClass();" class="sorter">#NiceToKnow</a>

<div id="cards1" class="nice">Test Content</div>
<div id="cards2" class="nice">Test Content</div>
<div id="cards3" class="nice">Test Content</div>
<div id="cards4" class="video">Test Video Content</div>
Hide result

DEMO

+2

- :

var elems = document.getElementsByClassName('nice');
for(var i = 0; i < elems.length; i++) {
    elems[i].style.display = 'none'
}

, getElementsByClassName.

jsfiddle

+1

, nice, none : https://jsfiddle.net/7vf9pz8u/

<script>
    function hide(){
    for(ct=0; ct < 3; ct++){
    document.getElementsByClassName('nice')[ct].style.display='none'
    }
    }
</script>
+1
source

getElementsByClassName returns an array of all matching elements, so you will need to specify an index or skip all of them to change their property.

Change your code to

document.getElementsByClassName('nice')[0].style.display='none'

// For each item

var e = document.getElementsByClassName('nice');
for (i = 0; i < e.length; i++) {
  e[i].style.display = "none";
}
0
source

Since your divs do not have unique names, they are in map arrays []. Therefore, to access a specific div, you need to reference the array to that particular div. The requested solution should work.

-2
source

Source: https://habr.com/ru/post/1613518/


All Articles