Since in javascript the + operator is used for both concatenation and addition, you need to put i+1 in a bracket, so that the first index gets increased and then you add it to p generate a unique id.
“p” + (i+1) will work
Since in javascript the + operator is used for both concatenation and addition, you need to put i+1 in a bracket, so that the first index gets increased and then you add it to p generate a unique id.
“p” + (i+1) will work
Replace:
sI[i].id = "p" + i + 1;
with:
sI[i].id = "p" + (i + 1);
If you want to do it more gracefully, you can use this
document.querySelectorAll("#article p").forEach(function(node,i){
node.id = 'p'+(i+1)
})
Adding brackets to isolate your addition will add and not concatenate
like so "p" + (i + 1)
var i;
var sI = document.querySelectorAll("#article p");
for (i = 0; i < sI.length; i++) {
sI[i].id = "p" + (i + 1);
}
<div id="article">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<div>
i have some <p>
inside <div>
, how to set ID
for all of them using for
loop?
HTML
<div id="article">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<div>
the result will be like that:
<div id="article">
<p id="p1">1</p>
<p id="p2">1</p>
<p id="p3">1</p>
<p id="p4">1</p>
</div>
i made this code but not working
var i;
var sI = document.querySelectorAll("#article p");
for (i = 0; i < sI.length; i++){
sI[i].id = "p" + i + 1;
}
“not working” really doesn’t describe a problem that anyone can help you with without wild guessing. Please clarify.
it’s pretty clear, please see Alexanderbira Answer, thank you.
Just because somebody took an educated guess and happened to give you the answer you wanted doesn’t make this question clear.
I have clarified what the target of the code is, and I have clarified the final result of the code, And I put my code so that I think it has a problem. I don’t know how to explain more, 4 people have answered, And I think that they all understood what is required from the code.
I work hard to improve my English, sorry for this misunderstanding.
@Aluan Haddad Thanks for pointing out. I have edited the answer