I have the following lines of code in my website:
HTML:
<div class="the-post-thumbnail">
<p><img src="http://placehold.it/350x150/FF0000/FFFFFF?text=Automatic+Thumbnail" alt="" width="" height="" /></p>
</div>
<div class="post-body">
<p><img src="http://placehold.it/350x150/00FF00/FFFFFF?text=Manual+Thumbnail" alt="" width="" height="" /></p>
<p>Paragraph</p>
<p><img src="http://placehold.it/350x150/0000FF/FFFFFF?text=Body+Image" alt="" width="" height="" /></p>
</div>
JavaScript/jQuery:
var ele = $('.post-body p:has(img):first');
if ($('.the-post-thumbnail img').length) {
ele.hide();
}
else {
ele.show();
}
What I am trying to do is:
- Check if there is an image within the
the-post-thumbnail
div and if so, hide the manual thumbnail image within thepost-body
- Check if there is not an image within the
the-post-thumbnail
div and if so, show the manual thumbnail image within thepost-body
This is partially working, however, what I’ve noticed is that if I remove the manual thumbnail image from within the post-body
div, it will remove the second body image after the paragraph tag as well.
How can I target just the manual thumbnail image which is directly within the post-body
div correctly so that I can achieve the two list items above, without adding additional classes?
FYI:
This is due to swapping my website’s theme for a different one. The older version required me to place in a thumbnail image for each post manually at the top of the article, and the new theme does this for me automatically. This resulted in duplicate images for older posts.
Working fiddle.
Just changing the position of
:first
selector should do the work, because it will select always the firstp
and check if it has an image :Hope this helps.
Without using any extra selectors, you could check for an image in the first paragraph.