Owais Ahmed
Owais Ahmed

Reputation: 55

Set different text to the same id divs

I have 3 divs with the same id and i need set values for them. The divs are generated dynamically and i want to set values.

<div id='product_0'>
<div id='product_name'>Product 1
</div>
</div>
<div id='product_1'>
<div id='product_name'>Product 2
</div>
</div>
<div id='product_2'>
<div id='product_name'>Product 3
</div>
</div>

The generated divs have default text and i want to change through jquery or javascript. Can anyone help me in this problem. Thanks in advance

Upvotes: 2

Views: 244

Answers (3)

Aaron Cicali
Aaron Cicali

Reputation: 1556

While I agree with some of the other answers in that IDs should be unique, you can still target these elements by simply adding the tag to your selector, like so:

<div id='testing'></div>
<div id='testing'></div>
<div id='testing'></div>

<script>
alert($('div#testing').length);
</script>

Here's a fiddle: http://jsfiddle.net/st9pz3qo/

Upvotes: 0

John R
John R

Reputation: 2791

Simply try like this using parent div id

 $("div#product_0").children("div").text("Product 4");
 $("div#product_1").children("div").text("Product 5");
 $("div#product_2").children("div").text("Product 6");

Upvotes: 1

4b0
4b0

Reputation: 22323

You are in wrong way. Dont use same id . Use Class.

Html:

<div id='product_0'>
    <div id='product_name0' class="product">Product 1</div>
</div>
<div id='product_1'>
    <div id='product_name1' class="product">Product 2</div>
</div>
<div id='product_2'>
    <div id='product_name2' class="product">Product 3</div>
</div>

Jquery:

$("div .product").eq(0).text("Product 4");
$("div .product").eq(1).text("Product 5");
$("div .product").eq(2).text("Product 6");

Working Fiddle

Upvotes: 1

Related Questions