August 17, 2013

giving id to many objects – is it a bad idea?

Sourabh’s Question:

I was working on a django project and soon the template became a mess and ended up with nearly all elements having an ID (just to clarify, all IDs are unique). I can reduce the number of IDs by giving their parents an ID but that would increase my jQuery code. So what I am asking is

Is it better to have many IDs in HTML or slightly less IDs and a bit longer JS/jQuery code?

Here’s a sample code:

<ol>
    <li>
        <p>
            <a href="/vote/" class="vote" id="story-vote-26"><img src="/static/images/arrow.gif"></a>
            <a href="http://www.lettersofnote.com/2012/10/people-simply-empty-out.html" class="title" id="story-title-26">“People simply empty out”</a> <span class="domain">(www.lettersofnote.com)</span>
        </p>
        <p class="story-info">
            <span id="story-points-26">660</span> points by tantaman ǀ 31 minutess ago
        </p>
    </li>
    ...

there are at least 100 of these li and each with 4 IDs (I haven’t added 4th one yet). So total of 400 IDs, or 100 IDs if I add ID to lis instead

There’s no problem in having many id. Hash algorithms used to look for elements scale very well.

So, as long as you don’t have performance problems that you could solve using id, the main rules to choose if you should add some id should be :

  • does it make the code more readable (a more concise code is often more readable) ?
  • does it make the code easier to evolve ?

Don’t make your code more complex just to add some id but there’s no hidden cost in having them.

The main purpose of IDs is to identify an element uniquely in DOM. It is mostly useful to pinpoint elements for using in JavaScript and CSS.

As long as, your application of these IDs are based on this rule, Its GOOD.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!