February 18, 2011

Check for duplicate DOM Id's with a simple JavaScript snippet

Yesterday I needed a cool, short and handy way of finding duplicate ID's inside the DOM of a webpage. I know there exist tons of extensions and validators but I wanted a solution with nearly no overhead.

The result is a tiny bookmarklet. After dragging it into my bookmarks bar I can analyse the current pages' DOM with one click on it.

I prepared one solution for prototype.js powered sites and one for jQuery.

If one has such an approach without relying on a 3rd party library feel free to contribute in the comments below.

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

JQuery version
(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');
    }
})();
Bookmarklet (Drag it to your bookmarks)

Hope it comes to some use!

4 comments:

  1. Very nice, thank you! However, this breaks (I was using the jQuery version) when there are form inputs with a name of "id" (because browsers allow inputs to be accessed via formObject.inputName). To get around this I added this at the beginning of the each function:
    if (typeof this.id != "string") return true;

    ReplyDelete
    Replies
    1. Actually, that wasn't the proper solution... instead, usage of this.id should be replaced with $(this).attr('id') so that it checks that form's actual ID.

      Delete
  2. Thanks for the nice article.
    But I've one question.
    What is prototype in JavaScript/Jquery?

    ReplyDelete
  3. JavaScript is the language future. The new JavaScript Version (Ecmascript 6) has been relaeased.

    JavaScript Online Training

    Javascript Online Training

    ReplyDelete