Solution 1 :

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

Solution 2 :

Replace:

sI[i].id = "p" + i + 1;

with:

sI[i].id = "p" + (i + 1);

Solution 3 :

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)
})

Solution 4 :

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>

Problem :

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;
     
}

Comments

Comment posted by Aluan Haddad

“not working” really doesn’t describe a problem that anyone can help you with without wild guessing. Please clarify.

Comment posted by Ahmad Adel

it’s pretty clear, please see Alexanderbira Answer, thank you.

Comment posted by Aluan Haddad

Just because somebody took an educated guess and happened to give you the answer you wanted doesn’t make this question clear.

Comment posted by Ahmad Adel

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.

Comment posted by Ahmad Adel

I work hard to improve my English, sorry for this misunderstanding.

Comment posted by Prakhar

@Aluan Haddad Thanks for pointing out. I have edited the answer

By

Leave a Reply

Your email address will not be published. Required fields are marked *