<p class="Links" onclick="window.location.href = 'file:///C:/Users/Dell/Desktop/Online%20Store.html#Residential'; document.getElementById('residence1, residence2, residence3').style.display='block'; document.getElementById('Commercial').style.display='none';">
Residential
</p>
I am trying but I fail to select more than one id using this method. Is my method correct or wrong?
I assume you're referring to this code:
You are able to select multiple elements with
.querySelectorAll()
which will return a node list that you can iterate over with.forEach()
So, for your example, you could do the following:
You can use query selectors to get multiple elements at once. Check this page out to get a brief list of how to use
querySelectorAll()
.In your case you can simply use
querySelectorAll("#id1, #id2, #id3")
which will return an array of all the elements matching these id'sIf you need to collect a bunch of elements based on more than one selector,
querySelectorAll
is your best friend.Unlike jQuery, querySelectorAll returns a
NodeList
type of object, similar to an array. To execute anything on each of the collection's members, you need to iterate over the collection yourself, e.g. usingforEach
:Please note that this addresses only your immediate syntactical needs; it merely fixes your (bad) approach.
What you should instead/not do:
hidden
attribute of HTML.Example:
Instead of doing
rather make sure your CSS has a class
.hidden
definedand then to show an element, remove the class from it, and to hide it, add the class:
As stated before, specifically for showing/hiding, the most simple thing to do is toggle the boolean
hidden
property of the element:or, if you prefer attributes over properties:
Also, as other have already stated, if you need to toggle the visibility of a whole collection of element, the best way is to give all those elements the same CSS class name (which makes it much easier to select):
I've also added the capability to rather toggle the visibility of the
.residence
div elements by not assigning a literal value toel.hidden
, but instead taking what's already inel.hidden
and inverting the boolean using the not operator!
.