Reputation: 9523
I have an HTML page where I would like to add elements to a specific list, like so:
<div id="list-of-divs">
<div id="name-specific-id">
// content
</div>
<div id="another-id">
//content
</div>
.
.
.
<div id="yet-another-id">
</div>
Now I want to add new div
s to that list, say with the following:
<div id="new-option-panel">
<input id="first-textbox-id" type="text">
<input id="second-textbox-id" type=text">
<button>Add new option</button>
Of course, the addition is done with jQuery code.
My question is: is it a good practice to add many such id
s in HTML code and depend on them in my jQuery code, or is it a bad practice for both HTML and jQuery, and I should find other ways in my jQuery code (depending on DOM traversing, for example)?
Just for example of what I mean: will adding to many id
s slow Javascript execution?
Upvotes: 5
Views: 1662
Reputation: 2105
Id selectors followed by Tag selectors are the best ones because they map directly to the native .getElementById()
and .getElementByTag()
methods
I would suggest that you always descend from the closest parent Id when you traverse the DOM. As in most languages there is always a readability/performance tradeoff that you will have to consider for your particular application.
Check out these performance guidelines for further insights
http://www.artzstudio.com/2009/04/jquery-performance-rules/
Upvotes: 1
Reputation: 94101
Id's are faster to query but very tedious to maintain, so I'd take the "performance hit" and make my code more obvious by using classes and id's only when necessary. In your example I would probably keep the id on the div but the input elements don't need one, a simple class will do for both jQuery and CSS or even no class at all.
Upvotes: 7