gorbe_js gorbe_js - 3 years ago 75
HTML Question

jQuery: Giving an id at the same time of element creation

Using a 'for' loop, let's say I want to make 4 different 'p' elements in the body with 4 different IDs. I approached the problem as follows:

for (var i = 1; i <= 4; i++) {
$("p").attr('id', 'paragraph' + i);

This was a very silly mistake on my part, heres why:

Every time the loop increments, it creates another p element, which is what I want it to do. However, it assigns ALL the p elements to the latest value of 'i'. So when the loop is executed all of of p elements would have a value of four.

My question is: Is there a way to assign the 'p' element's ID to the current value of 'i' when the 'p' element is appended?

To be clear, this is my goal:

<p id="paragraph1"></p>
<p id="paragraph2"></p>
<p id="paragraph3"></p>
<p id="paragraph4"></p>

But doing it through jQuery without editing the actual HTML file.

Answer Source

it's selector problem

$("p:last").attr('id', 'paragraph' + i);

will select last p html tags and give it the current i value

check this link

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download