How could I do the oposite with this function

hello i would like to hide the elements applying an display= ‘none’ to the function but when I do it really dosn’t work
js

function showAll() {
    var arrayOfElements=document.getElementsByClassName('hid');
    var lengthOfArray=arrayOfElements.length;

    for (var i=0; i<lengthOfArray;i++){
        arrayOfElements[i].style.display='block';
    }
}

If you want to hide it, it would be display='none';.

I did that already but is not working :neutral_face:

Is there a demo? i don’t see why it wouldn’t work.

html

<div id="box" class="boxStyle">
	<button onclick="remove()">Remove all</button>
	<button onclick="showAll()">Show all</button>
	<button id="showMeGirls">Show me girls</button>	
	<div id="girls" class="hid">
	  <img src="girl1.jpg">
	  <img src="girl2.jpg">
	</div>
	<button id="showMeBoys">Show me boys</button>	
	<div id="boys" class="hid">
	  <img src="boy1.jpg">
	  <img src="boy2.jpg">
	</div>
</div>

css

.hid {
	display: none;
}

js

function remove() {
    var arrayOfElements=document.getElementsByClassName('hid');
    var lengthOfArray=arrayOfElements.length;

    for (var i=0; i<lengthOfArray;i++){
        arrayOfElements[i].style.display='block';
    }
}

i would like to hide the hid div but when i use display none dosn’t work, i know i should remove block and put none but is not working

This is strange, I’m looking into it. I have this demo setup: https://jsfiddle.net/arvw0xk2/

I got it working, it had to do with the way JSFiddle handles JavaScript. Make sure you put the code at the end of the body tag, and that it’s not wrapped with any function like window.onload.

ok thanks alot gonna see if works thanks alot men was very useful:grinning:

1 Like

Avoid using .onclick() use .addEventListener() instead…

1 Like

whats the disadvantage of using .onclick() instead of .addEventListener() please

Quoted from developer.mozilla.org:

Note that each object can have only one on-event handler for a given event (though that handler could call multiple sub-handlers). This is why addEventListener() is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.

There are other reasons too, like using event bubbling, but it’s kind of rare to use event bubbling.

I updated the fiddle to use addEventListener. New link: https://jsfiddle.net/g9mLpt5v/2/

.onclick() is a property. Thus it can be overwritten unintentionally.

.addEventListener() can stack. Allowing you to have multiple click events.

1 Like

thats very handy thanks alot for the info

1 Like