Reputation: 92
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.
Upvotes: 0
Views: 134
Reputation: 7
put this line outside the loop var secId = 0; cause each time you enter the looop and declare the variable and set 0 and add (1) and set to a new section
Upvotes: 1
Reputation: 45135
You are resetting the secId
each time in your for
loop. So it's always going to be 1
. Don't do that. In fact, you don't even been secId
at all because you have the your array index. So in your loop you could do something like:
sec[i].id = "section_" + i;
Or if you really want it to start at 1
:
sec[i].id = "section_" + (i+1);
I added the prefix of section_
just because using just the number is likely to clash if you have multiple bits of code doing something similar
Upvotes: 1
Reputation: 104775
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;
}
Upvotes: 3