Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 388
ManUO Avatar asked Mar 23 '23 22:03

ManUO


1 Answers

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/

like image 135
Ian Avatar answered Mar 29 '23 23:03

Ian