2

Because I don't have a strict naming convention for divs, spans, and inputs, I frequently give more than one input the same id by accident, which of course causes jQuery/javascript code to not work.

Giving more than one element the same id is not allowed, but I don't see any kind of error message anywhere when it happens, so when I do this it sometimes takes a lot of time before the "oh duh" moment where I realize what I did.

Is there any way to know when more than one element has the same id?

Nate
  • 26,164
  • 34
  • 130
  • 214
  • Previous answer [link](http://stackoverflow.com/questions/482763/jquery-to-check-for-duplicate-ids-in-a-dom) – mconlin Apr 12 '13 at 22:43

5 Answers5

3

This is going to be a standard practice you're going to learn through writing HTML over and over, time and time again! A good way to avoid using duplicate ID's would be to use less ID's and maybe use classes in their place.

Only use ID's for important/structural elements on your website such as #header, #footer, #main, #slideshow, #content, #sidebar, etc.

If you're repeating ID's over and over on a page maybe you should be using classes. Any element/styled module that is going to be reused on that a multiple times should be identified using a class.

Also, some IDE's will perform some special syntax highlighting/text-decoration to let you know that something funky is going on. Two that come to mind immediately are SublimeText2 and Visual Studio.

Here's a jQuery snippet you can run to check for duplicate ID's on a page. It will let you know in your Console (F12 developer tools/Firebug) if there are any duplicates on the page.

(function () {  
    var found = false;  
    $('[id]').each(function () {  
        var ids = $('[id=' + this.id + ']');  
        if (ids.length > 1 && ids[0] === this) {  
            console.warn('ID used more than once: ' + this.id, ids);  
            found = true;  
        }  
    });  
    if (!found) {  
        console.log('No duplicate IDs found');  
    }  
})();  

You could throw this in your global footer so that it runs on every page, just be sure you take it out before going to production.

Here's a JSFiddle: http://jsfiddle.net/A7h75/

Got the script from here.

kyle.stearns
  • 2,326
  • 21
  • 30
  • Good advice, but I'm just getting started with AJAX applications and as far as I can tell the only way to update the content of spans, divs, and inputs is to assign them an id. So lots and lots of elements have to have ids. – Nate Apr 13 '13 at 00:19
  • @kyle.stearns I'm using PhpStorm. – Nate Apr 13 '13 at 00:23
  • @Nate Couldn't find any syntax highlighters that would provide the behavior you're looking for. I've updated my answer with a possible solution. – kyle.stearns Apr 13 '13 at 01:06
  • @nate you don't need to use IDs **any** selector will do, as long as you are able to find the right element via JavaScript, e.g. `$('div.something').find('span.blah').html('Look mom!');` will work. Just google a bit for examples. IDs may *help* to make it easier in some situations – thaJeztah Apr 13 '13 at 09:31
1

A good IDE will catch this for you. I use Zend Studio (which is essentially a PHP specific version of Eclipse) and it will catch this for you as you write your code. That's about as soon as you can catch it.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Add [PhpStorm](http://www.jetbrains.com/phpstorm/) to this list. Although I think any proper IDE will validate your HTML, it will not always validate properly if the content is generated dynamically (e.g. A *list* of articles output by a PHP loop). For proper validation, I tend to use browser plugins for validation – thaJeztah Apr 12 '13 at 22:53
  • @thaJeztah - I actually am using PhpStorm, but it doesn't seem to make any fuss when I use the same id on more than one element. I do generate some of the page output via PHP, so I think I might give a FF plugin a try. – Nate Apr 13 '13 at 00:17
  • @Nate interesting that it doesn't find that problem, not behind my computer now, but will check if it doesn't (otherwise will post a feature request/bug report with JetBrains as that clearly will be an omission!) – thaJeztah Apr 13 '13 at 09:24
1

You can check if your HTML is valid via the W3C Validator Service

This will show you all errors in your HTML and is advisable anyway just to check your HTML for errors that may cause cross-browser rendering problems

Various extensions exist for Firefox and Chrome to check your HTML without having to visit the Validator service 'manually'

thaJeztah
  • 27,738
  • 9
  • 73
  • 92
0

you could utilize this function to check for duplicates

function getDuplicateIds(){
    var dups = [];
    $('[id]').each(function(){
        if($('[id="'+$(this).attr('id')+'"]').length > 1) dups.push($(this).attr('id'));
    })
    return $.unique(dups);
}
Ejaz
  • 8,719
  • 3
  • 34
  • 49
-1

There's no way to turn on errors for this, but in a specific circumstance:

$('[id={elementId}]').length > 1

should do the trick.

Edit: thanks for the correction.

Doug
  • 2,441
  • 2
  • 19
  • 22