For example, I have a website which has a dynamically-generated segment of its dom which looks roughly like this:
<div id="master">
<div class="child"> ... </div>
<div class="child"> ... </div>
<div class="child"> ... </div>
...
<div class="child"> ... </div>
</div>
There might be hundreds of child elements in this manner, and they, too, might have yet more children. At present, none of them have id’s except for the master. Javascript manipulates them via dom-walking. It’s a little scary.
I’d like to add id’s, e.g.:
<div id="master">
<div id="child1" class="child"> ... </div>
<div id="child2" class="child"> ... </div>
<div id="child3" class="child"> ... </div>
...
<div id="childN" class="child"> ... </div>
</div>
What are the tradeoffs in adding id’s to these divs? Certainly, jQuery must maintain a hash of id’s, so there’s going to be some sort of performance hit. Any general guidelines in when adding additional id’s is a bad idea? Is jQuery so awesome that, in practice, it doesn’t matter?
Nope. It’s the browser that (optionally, as an optimisation) keeps a lookup of
idto node.If you interact with objects in a way that causes jQuery to add
datato an element (including if you add an event listener), then it will add its own jquery-id to the element for lookup purposes. But it’ll do that regardless of whether the element has anidattribute.Add
ids if you need to pick out a particular element from the rest. But there’s no point in addingchildNattributes to every child when you already have classes. The selector#master>.childis likely to be faster than#master>[id^=child], and certainly much faster than fetching eachidNseparately in a loop.