Reputation: 55
I can't figure out how to add html after the second image on a page.
My code is working fine if I target <p>
, <div>
or whatever, but not images.
I don't get any error in console.
Here my JS :
$("#blog-main > img:nth-child(2)").append("<div>inserted div</div>");
And html is like this :
<div class="col-sm-8 blog-main" id="blog-main">
<p></p>
<img src="" />
<p></p>
<img src="" />
</div>
Can someone help me on this one ? Solution must be really simple, but I can't figure it out.
Upvotes: 1
Views: 158
Reputation: 115222
Use :eq(1)
to select second img tag and use after()
to add content after the img tag
$("#blog-main > img:eq(1)").after("<div>inserted div</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="col-sm-8 blog-main" id="blog-main">
<p></p>
<img src="" />
<p></p>
<img src="" />
</div>
Upvotes: 2
Reputation: 11416
Alternatively to using :eq()
, you can also use :nth-of-type()
:
$("#blog-main > img:nth-of-type(2)").append("<div>inserted div</div>");
Upvotes: 1
Reputation: 5178
:nth-child()
looks for all elements inside #blog-main
, not only for img
. Use :eq()
instead:
$("#blog-main > img:eq(1)").append("<div>inserted div</div>");
Update. Yes, I forgot that you need to add element after <img>
, not into it, so it should be, for example, .after()
instead of .append()
:
$("#blog-main > img:eq(1)").after("<div>inserted div</div>");
Upvotes: 1