Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the javascript performance tradeoffs in adding id's to dom elements?

Tags:

html

jquery

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?

like image 298
Jude Allred Avatar asked May 12 '26 14:05

Jude Allred


1 Answers

Certainly, jQuery must maintain a hash of ids

Nope. It's the browser that (optionally, as an optimisation) keeps a lookup of id to node.

If you interact with objects in a way that causes jQuery to add data to 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 an id attribute.

Add id​s if you need to pick out a particular element from the rest. But there's no point in adding childN attributes to every child when you already have classes. The selector #master>.child is likely to be faster than #master>[id^=child], and certainly much faster than fetching each idN separately in a loop.

like image 183
bobince Avatar answered May 14 '26 09:05

bobince