1

I want to add a functionality on click event. I want to display none four div but this code seems doesn't work for me Please tell me the mistake in this

<a class="lightbox-close" href="#" onclick="document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4').style.display = 'none';"></a>
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
Rupesh Arora
  • 557
  • 2
  • 9
  • 26

2 Answers2

2

The querySelectorAll returns a NodeList, you need to iterate over it and set the properties.

So it will be better to write a separate function where you can write the iteration logic

var els = document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4');
for (var i = 0; i < els.length; i++) {
    els[i].style.display = 'none';
}
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Query selector is not like jQuery selector where you can do

$('#goofy_1,#goofy_2,#goofy_3,#goofy_4')// it will get you all div selected 

Instead Query selector returns nodeList which means you are getting

try console log your querySelectorAll

 console.log( querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4'));

you will get something like

i.e i am selecting a

enter image description here

now you can see that there isnt single element selected so you can directly make any changes

Now you need to loop through all element like Arun P Johny telling

var allElements = document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4');
for (var i = 0; i < els.length; i++) {
    allElements [i].style.display = 'none';
}

Good Read

Difference between HTMLCollection, NodeLists, and arrays of objects

Community
  • 1
  • 1
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143