ManUO
ManUO

Reputation: 347

JavaScript get h1 elements in HTML document and update unique IDs

I have a legacy html document containing h1 elements which don't have ids. What I would like to achieve is to be able, using JavaScript, to get all h1(s) and then add to each a unique ID.

I have searched but could not find a solution that works.

Upvotes: 6

Views: 27624

Answers (2)

Ian
Ian

Reputation: 50923

Try getting all of them with document.getElementsByTagName("h1"). Loop through them, check if they have an id, and work appropriately. Try:

var h1s = document.getElementsByTagName("h1");
for (var i = 0; i < h1s.length; i++) {
    var h1 = h1s[i];
    if (!h1.id) {
        h1.id = "h1" + i + (new Date().getTime());
    }
}

DEMO: http://jsfiddle.net/kTvA2/

After running the demo, if you inspect the DOM, you'll see 3 out of the 4 h1 elements have a new, unique id. The one with the id in the first place isn't changed.

Note that this code needs to run after all elements are ready/rendered, which can be achieved by putting the code inside of a window.onload handler. The demo provided is set up to implicitly run the code then.


UPDATE:

With jQuery, you could use:

$(document).ready(function () {
    $("h1:not([id])").attr("id", function (i, attr) {
        return "h1" + i + (new Date().getTime());
    });
});

DEMO: http://jsfiddle.net/kTvA2/7/

Upvotes: 8

km6zla
km6zla

Reputation: 4897

Use querySelectorAll() to get all of your header elements, then iterate over the result and generate yor unique id for each element.

var headerElements = document.querySelectorAll('h1');
for(h in headerElements) {
    if(headerElements[h] instanceof Element) {
        headerElements[h].id=uniqueIDgenerator();
    }
}

Upvotes: 1

Related Questions