Handling multiple IDs in jQuery

JqueryJquery Selectors

Jquery Problem Overview


Can multiple ids be handled like in the code?

<script>
$("#segement1, #segement2, #segement3").hide()
</script>

<div id="segement1"/>
<div id="segement2"/>
<div id="segement3"/>

Jquery Solutions


Solution 1 - Jquery

Yes, #id selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.

However, for your example, since <script> comes before the elements, you need a document.ready handler, so it waits until the elements are in the DOM to go looking for them, like this:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

Solution 2 - Jquery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector. > elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable. > $(elem1,elem2,elem3).css({'display':'none'}); // will not work

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajeevView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryZeeshan EqbalView Answer on Stackoverflow