Reputation: 635
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:
the-post-thumbnail
div and if so, hide the manual thumbnail image within the post-body
the-post-thumbnail
div and if so, show the manual thumbnail image within the post-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.
Upvotes: 2
Views: 88
Reputation: 67505
Just changing the position of :first
selector should do the work, because it will select always the first p
and check if it has an image :
var ele = $('.post-body p:first:has(img)');
Hope this helps.
Upvotes: 2
Reputation: 11
Without using any extra selectors, you could check for an image in the first paragraph.
var ele = $('.post-body p:eq(0):has(img)');
Upvotes: 1