views:

39

answers:

3

Hello, 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

+1  A: 

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');
    }
});
Delan Azabani
So it would be $("img:first .entry-content") ?
No. That would select all the `.entry-content` nodes in the first `img`. Actually, I'm not sure you can even put `:first` there. What you need to do is select `.entry-content`. Then you loop through each of these and select the `img:first` inside it.
Delan Azabani
I'm just unsure of how to select entry-content, then img:first for each instance of it? Is that another line in the jq?
I've edited my post to include some code which might work for you.
Delan Azabani
-1 querySelectorAll is not yet implemented into all a-grade browsers.
roosteronacid
Internet Explorer is not an A-grade browser. Even if you think it is, babysitting the browser using general libraries such as jQuery just slows down the process of people migrating to other browsers even further! If we want to guide users away from IE, we need to start by not hacking our programs to work with it.
Delan Azabani
That's not an argument (although I somewhat agree in the space of progressive enhancement). Real world: if you want to make money off a web application; you need to include support for Internet Explorer (I can haz largest user-base?). I hate IE as much as the next guy. But that's just how it is.
roosteronacid
A: 

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');
});
Paul Dragoonis
A: 

A variation of Paul Dragoonis' answer:

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