Home » Wordpress » jQuery addclass to each WordPress post image

jQuery addclass to each WordPress post image

Posted by: admin November 30, 2017 Leave a comment

Questions:

this is what I have so far:

<script>
$(document).ready(function(){
    $(".entry-content img:first").addClass('postimage');
});
</script>

As you can see, for the first image of .entry-content it adds my class. Cool, that works fine. Uncool, it doesn’t work for every post but only the first on the page.

I’m not sure how to fix this. Do I need to use .each in some way or is there something wrong with what I have already?

Thanks

Answers:

This is because the CSS selector is selecting the first .entry-content img, not the first img in every .entry-content. It’s about operator precedence.

You can iterate through each .entry-content and select the img:first in that node manually, though.

$(document).ready(function(){
    var entries = document.querySelectorAll('.entry-content');
    for (var i = 0; i < entries.length; i++) {
        var firstImage = $(entries[i].querySelectorAll('img:first')[0]);
        firstImage.addClass('postImage');
    }
});

Questions:
Answers:

this will iterate over all your posts and apply the class to the first image within each.

$.each('.entry-content', function() {
    $(this).find('img:first').addClass('postImage');
});

Questions:
Answers:

A variation of Paul Dragoonis’ answer:

$(".entry-content").each(function ()
{
    $("img:first", this).addClass("postImage");
});