84

Can multiple ids be handled like in the code?

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

<div id="segement1"/>
<div id="segement2"/>
<div id="segement3"/>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Rajeev
  • 44,985
  • 76
  • 186
  • 285

2 Answers2

147

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>
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • If there are no contents for div we can just write
    right?
    – Rajeev Jan 05 '11 at 13:11
  • 3
    @Rajeev - nope, it's not a self-closing element :) – Nick Craver Jan 05 '11 at 13:11
  • What if these divs are generated automatically #segment{i} and there are an undefine quantity of them ? – Reveclair Jan 30 '14 at 15:58
  • 2
    @Reveclaire If you had to, use a ["starts with" attribute selector](http://api.jquery.com/attribute-starts-with-selector/) like this: `$("[id^=segement]").hide()` (scoping it a bit to whatever the parent is wouldn't be a bad idea). – Nick Craver Jan 30 '14 at 16:01
1

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

Zeeshan Eqbal
  • 245
  • 2
  • 11