Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML DOMs, ids vs no ids?

Provided you have a container div with hundreds of very simple children elements such as the following:

<div id="stuffContainer" class="item-container">
    <div class="single-item"></div>
    <div class="single-item"></div>
    <div class="single-item"></div>
    <div class="single-item"></div>
    <div class="single-item"></div>
    <div class="single-item"></div>
    [...]
</div>

Would including an unique id for each single element harm (client) performance in any (meaningful) way, be it rendering, javascript or memory wise?

Why I'm asking: I may need from time to time to reference specific items, and I'm trying to figure out whether I should precalculate in advance which items I will need to select, giving ids to them and leaving the rest out, or just assigning ids to all of them, which would make the process more straight forward but I wonder if this may be an overkill somehow.

Bonus points (if I could actually give them) if someone can talk about how this is handled by modern browsers and why it would/would not make a difference in terms of how browsers render and manage the DOM.

like image 276
Mahn Avatar asked Aug 07 '12 22:08

Mahn


2 Answers

At the very most, I'm guessing that the basic few things a browser would do is assign the ID as a property to each element when building the DOM structure, as well as store the IDs in a hash table to facilitate things like #id selectors, document.getElementById() and idref lookups later. I don't think this is going to cause even a slight dent in observed performance or memory usage, as hash tables and the DOM are designed to be very well-optimized.

That said, if IDs aren't needed on your elements at all, then there quite simply is no point in assigning them IDs; you're going to end up with a whole lot of markup bloat instead. As Dan Davies Brackett mentions, that will obviously cause a slowdown since it depends on the client connection.

If you can afford to reference these elements using CSS selectors, you can always use :nth-child() to look up specific children. If you need to support older browsers, there's always a CSS2 solution. See these questions:

  • How can I get the second child using CSS?
  • How do I get the nth child of an element using CSS2 selectors?
like image 61
BoltClock Avatar answered Sep 28 '22 07:09

BoltClock


As BoltClock implies, the answer to most performance questions is 'measure it!'. That said, you missed one potential axis for measurement: download size. Adding ID attributes to more elements than is necessary will add to your byte weight, not least because the elements are required to be unique (which means they won't zip as well as non-unique attributes might).

like image 40
Dan Davies Brackett Avatar answered Sep 28 '22 09:09

Dan Davies Brackett