The definitive ID experiment

The definitive ID experiment

I copied this from a response of mine. I think it deserves it's own post. Here's a little experiment you can to do to understand why using IDs is a problem in jQuery Mobile. 

I haven't put this in a jsFiddle, etc, because I want to keep it as dead-simple as possible. I want people to create a file locally and experiment with their browser console. (Or, if you prefer, add console.log statements.)

------

Try the following simple example. You only need a simple page, and jQuery (don't need jQuery Mobile) and your browser's Javascript console for test:

  1. <!DOCTYPE html>
  2. <html lang="en" >
  3.   <head>
  4.     <meta charset="utf-8" />
  5.     <title>ID Test</title>
  6.     <script src="jquery-1.8.3.min.js"></script>
  7.   </head>

  8.   <body>
  9.     <div class="first" id="a">This is the first div</div>
  10.     <div class="second" id="a">This is the second div</div>
  11.   </body>

  12. </html>

Now, go to your Javascript console, and type in this:

$("#a")

How many items do you see in the result list? Did you expect to see two? Do you see two? What item(s) do you see?

Hint: you will see ONE. Which one you see is browser-dependent. In fact, with some browsers, you might not even see any, because this is a invalid condition. What should the browser do with an invalid condition?

EVERYBODY READING THIS FORUM SHOULD TRY THIS EXPERIMENT.

Then, forgot about using IDs. Or, at least, duplicating them. Keep in mind that JQM always loads at least two pages in the DOM at once, at least if you ever change pages. The old page and the new page. Also, the first page visited always stays in the document. If you are making a website, the user might enter the site from any page, so you really need to make sure you never duplicate an ID on *any* page.

If you want to use IDs in your project, have fun making sure you never duplicate one in any pair of pages that might be loaded together. (This might include the *same* page if you ever do a same-page transition...) It's a lot easier not to ever use IDs.

For extra credit, try this in the console:

$("[id=a]")

This time, you will get a list of two elements.

So, should you still use IDs, and use this construct instead of  $("#a")?


Well, you can do that if you are simply stubborn. It is one of the slowest queries - much slower than a class query. You lose any benefit from using IDs.

Extra-extra credit: extend the experiment. Load jQuery Mobile as well, and experiment with IDs duplicated on two or more pages. What happens now?