if I have this html
<div>
<p>1</p>
</div>
<div>
<p>1</p>
<p>2</p>
</div>
and this jquery
$('div').each(function () {
$(this).find('p').eq(1).html('test');
});
i get this
<div>
<p>1</p>
</div>
<div>
<p>1</p>
<p>test</p>
</div>
what jquery should I use to get this instead?
<div>
<p>1</p>
<p>test</p>
</div>
<div>
<p>1</p>
<p>test</p>
</div>
there is no match for eq(1) on the first div so it just skips it. how can I add a child if none exists or update it if one does exist, without having to split the jquery into several statements?
If your
<div>elements contain at most two paragraphs, you can do:If there are more than two paragraphs, things get more complicated and you’ll have to use insertAfter() instead of appendTo() to add the new element to the DOM:
You can see the results in this fiddle.