Suhail Gupta
Suhail Gupta

Reputation: 23216

Does append work only for the first found element?

Does append work only for the first found element?

<div id='parent'> <strong> </strong> </div>
<div id='parent'> <strong> </strong> </div> 

$('#parent').append('Text inside div');

I could see Text inside div printed only once when I run the html.

PS : This works :

$('#parent>strong').append('Text inside div');

It prints the text twice.

Upvotes: 0

Views: 95

Answers (5)

PHP Worm...
PHP Worm...

Reputation: 4224

it is already working as you want because you are using ID so it will automatically applied on first found child

<div id='parent'> <strong> sadsadsadsa</strong> </div>
<div id='parent'> <strong>sdsadsadadasd </strong> </div> 
$('#parent').append('Text inside div');

demo: http://jsfiddle.net/ishandemon/duhLnq0s/3/

Upvotes: 0

Luthando Ntsekwa
Luthando Ntsekwa

Reputation: 4218

Remember : ID's are unique

  • Each element can have only one ID
  • Each page can have only one element with that ID

Classes are NOT unique

  • You can use the same class on multiple elements.
  • You can use multiple classes on the same element.

So what you need is :

<div class='parent'> <strong> </strong> </div>
<div class='parent'> <strong> </strong> </div> 

Instead of :

<div id='parent'> <strong> </strong> </div>
<div id='parent'> <strong> </strong> </div> 

And your Jquery will be like:

$('.parent').append('Text inside div');

Upvotes: 0

Vivek Gupta
Vivek Gupta

Reputation: 1055

When you use same Id for more than one html element script picks the first one it encountered in flow.

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

IDs should be unique.$('#parent') will only return first element in matched set. You need to use common class selector instead:

 <div class='parent'> <strong> </strong> </div>
 <div class='parent'> <strong> </strong> </div> 

JS:

 $('.parent').append('Text inside div');

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

Use classes instead of id, because ID must be unique

$('.parent').append('Text inside div');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'> <strong> </strong> </div>
<div class='parent'> <strong> </strong> </div>

Upvotes: 2

Related Questions