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.
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.
Share Improve this question edited May 16, 2013 at 15:37 Ian 50.9k13 gold badges103 silver badges111 bronze badges asked May 16, 2013 at 15:31 ManUOManUO 3473 gold badges5 silver badges18 bronze badges 3- What format do you want the IDs in? And can you provide some example HTML? – MasNotsram Commented May 16, 2013 at 15:33
- 2 You can access any DOM element without an ID. Why do you need to do this? – Diodeus - James MacFarlane Commented May 16, 2013 at 15:33
- 1 Why? I can think of several reasons why you might want to, but the ones that might be useful would impose additional requirements beyond "unique". What problem are you trying to solve? If we know that, we can address the problem instead of what you think the solution is. – Quentin Commented May 16, 2013 at 15:34
2 Answers
Reset to default 8Try 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/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/kTvA2/7/
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();
}
}