EL S EL S - 2 months ago 12
HTML Question

How to set unique id to multiple tags with javascript

I have a page where there are multiple

<section>
tags, what I want to do is to assign to each one of them an unique id.

<body>
<button id="set" onclick="setIds()">SET</button>
<div id="d1">
<section>1</section>
<section>2</section>
<section>3</section>
<section>4</section>
<section>5</section>
<section>6</section>
<div id="demo"></div>
<script>
var sec = document.getElementsByTagName('section');

function setIds(){
for(var i = 0; i < sec.length; i++){
console.log(sec[i].id);
var secId = 0;
secId += 1;
sec[i].id = secId;
}}
</script>
</body>


I'm still learning javascript, so, I've tried using this code and it just adds the same id for all sections. Any help would be much appreciate.

Answer

It's because each loop you reset secId to 0. If you declare it outside the loop and only increment each loop, it'll work:

var secId = 0;
for(var i = 0; i < sec.length; i++){
    console.log(sec[i].id);

    secId += 1;
    sec[i].id = secId;
}