I have a problem in HTML, where a lot of elements needs ids. It is very tedious to manually change/set each one. Is there a good way in HTML/JS to generate ids for elements according to a pattern? In the picture below I have the "H1_b" ids that all has to be incremented by 1 so that you get "H2_b" etc...
Best regards
CodePudding user response:
Here is the function to easily defined IDs of a particular tag name:
const generateIdsForTagName = (tagName) => {
const elems = document.querySelectorAll(tagName)
elems.forEach((elem, i) => elem.setAttribute('id', `${tagName}_${i}`))
}
// generateIdsForTagName('h1') -> you can see all your h1 will contain different ids
CodePudding user response:
Iterate over elements.
var spans = document.getElementsByTagName("SPAN");
for (var i = 0; i < spans.length; i ) {
spans[i].id = "a" i;
}
console.log(document.getElementsByTagName("MAIN")[0].outerHTML);
<main>
<span>This is a test.</span>
<span>This is a test.</span>
<span>This is a test.</span>
<span>This is a test.</span>
</main>
CodePudding user response:
I recursively iterate the entire elements tree giving id for each element who has no id or a non unique id.
var id_index = 0;
var seen = {}
function give_id(elem) {
if (!elem.id || seen[elem.id]) {
elem.id = "id-" id_index ;
} else {
seen[elem.id] = true;
}
var children = Array.from(elem.children);
children.forEach(give_id)
}
give_id(document.body)
console.log(document.body.outerHTML)
<body>
<div></div>
<div id="already"></div>
<div id="already"></div>
<div></div>
</body>