Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling multiple IDs in jQuery

Can multiple ids be handled like in the code?

<script> $("#segement1, #segement2, #segement3").hide() </script>  <div id="segement1"/> <div id="segement2"/> <div id="segement3"/> 
like image 267
Rajeev Avatar asked Jan 05 '11 12:01

Rajeev


People also ask

Can we add multiple ID in jQuery?

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

Can you assign multiple ids to an element?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.

Can you have multiple ids in Javascript?

You could implement your own function that takes multiple ids and returns multiple elements. You could use document. querySelectorAll() that allows you to specify multiple ids in a CSS selector string . You could put a common class names on all those nodes and use document.

Can a div have multiple ids?

While you can give a div multiple ids, only one will be applied by the browser. The second id or any other id after the first one will just be ignored by the browser. So having multiple ids for a div is not only pointless but is also incorrect HTML.


2 Answers

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> 
like image 145
Nick Craver Avatar answered Oct 06 '22 02:10

Nick Craver


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

like image 43
Zeeshan Eqbal Avatar answered Oct 06 '22 00:10

Zeeshan Eqbal