admin管理员组

文章数量:1415099

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 divs 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 ids 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 ids slow Javascript execution?

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 divs 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 ids 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 ids slow Javascript execution?

Share Improve this question edited Jan 26, 2013 at 16:16 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Jan 26, 2013 at 10:31 Tamer ShlashTamer Shlash 9,5236 gold badges45 silver badges87 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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.

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./2009/04/jquery-performance-rules/

本文标签: javascriptHTMLJS good practices Is it good to add too many idsStack Overflow