What's The Difference Between Class And Id In JQuery?
Solution 1:
ID's should be unique on the page, when you have multiple elements with same ID's, jQuery selects only the first one. That's because it doesn't have to bother looking for others as there isn't supposed to be any more – that might explain the weird behaviour you're experiencing.
If you want multiple elements to have the same functionality, give them the same class. If you want to identify a specific element, give it an id. This isn't limited to just jQuery, but to HTML and CSS overall.
Solution 2:
I don't think this distinction is really a jQuery thing -- jQuery simply "borrows" its selector syntax from HTML/CSS.
The biggest difference: ids are meant to be unique, classes are not.
Check out this article for a lengthy, comprehensive treatment of this question.
Solution 3:
Classes and IDs come from CSS. IDs are supposed to be unique within your HTML document (think "mainmenu"), classes can be used multiple times within the same document. IDs usually identify a unique item within your document where as classes help apply a common style to multiple items across the page.
So if you want to hide, say all links with the "green" class you can do:
$('a.green').hide();
And then all links with the "green" class will hide. Whereas if you want to hide a specific item with an ID (say <div id="mainmenu">) you'd do:
$('#mainmenu').hide();
Solution 4:
An element can have multiple classes and multiple elements can have the same class, however, only one element can have a specific ID. (If you define multiple elements with the same ID, jQuery will only return the first).
Valid:
<span class="myclass myclass2 mycall3"></span>
<span class="myclass"></span>
<span id="myspan"></span>
ID refers to a specific control, therefore, only ONE control should have a specific ID.
If you have the following:
<span id="myspan">Hello</span>
<span id="myspan">Goodbye</span>
If you select the following using jQuery
$("#myspan").html();
jQuery will select the first one and return Hello
Side note: classes and ids have nothing to do with jQuery and everything to do with valid HTML. jQuery and CSS use these conventions to select specific elements.
Solution 5:
Id is uniquely identify an element on the webpage, irrespective of its type (button, div, radio etc.) where as Class is used to identify a certain type of elements.
cheers
Post a Comment for "What's The Difference Between Class And Id In JQuery?"