user9504869
user9504869

Reputation:

Dynamic ID in Javascript

I am making something where I have dynamic ID for element i.e something like this in my index.ejs

<% for ( var i= 0; i<100; i++ ) { %>
     <th> <span class="Pr" id=price"<%=i%>">$<%= result[i]["price"] %></span></th>
<%} %>

This should generate ID which increments with i for example price1, price2 and so on..

Now I am using Socket.io to obtain new data. After obtaining the new data, I want to change the innerHTML

Traditionally, I know I can do something like

 document.getElementsByID("id").innerHTML = newData; 

But I knew the ID there well in advance, Here the ID obtained is when the data obtained from socket.io matches my iTH element

document.getElementById('price' + i).innerHTML

I was hoping that this would make my ID as price0, price1, price2 (when i=0,1,2) but this doesn't seem to be working.

Please do let me know how I can fix this?

Upvotes: 2

Views: 1055

Answers (2)

MrCode
MrCode

Reputation: 64536

There appears to be quotes in your id attribute, which would produce ids like

id=price"0"
id=price"1"
id=price"2"

As you can see that is incorrect formatting. Change to:

id="price<%=i%>"

Which will produce the correctly formatted attributes:

id="price0"
id="price1"
id="price2"

Upvotes: 1

Mohammad Ali Rony
Mohammad Ali Rony

Reputation: 4925

I try dynamic ID using your code it is working fine.

You can see this

for (let i = 0; i < 4; i++) {
    document.getElementById('price' + i).innerHTML ="test";
}
<span class="Pr" id="price0">price0</span>
<span class="Pr" id="price1">price1</span>
<span class="Pr" id="price2">price2</span>
<span class="Pr" id="price3">price3</span>

Upvotes: 0

Related Questions