tags:

views:

48

answers:

3

Hello,

I'm using (trying to use) jQuery to add a class to the first paragraph of every div with class of ".djBio" My problem is that it's only adding the class to the first div.djBio, not all divs with that class. Here's the code. I am also using the fancy letter jquery plugin to add the drop cap to the first paragraph (which also is only applying to the first div.djBio, not all)

jQuery(function( $ ){
    $('.servicesContent p:first, .about-usContent p:first, .djBio p:first').fancyletter().addClass('firstP');
});

Thanks so much for your help!

+4  A: 

You've stumbled over what everyone stumbles over at some point: :first doesn't really mean what you (at first) think it means. :first will only ever return (at most) one element. The best way I can think of doing your problem is using each():

$(function() {
  $(".servicesContent, .about-usContent, .djBio").each(function() {
    $(this).find("p:first").addClass("...");
  });
});
cletus
awesome, that helps alot!
j-man86
+2  A: 

You can rewrite the code like this to add the class to all of the first p tags:

$('.servicesContent, .about-usContent, .djBio').each(function() {
    $(this).find('p:first').fancyletter().addClass('firstP');
});

The problem with your code is it finds only the first instance of a p tag within a element with the given class.

wsanville
A: 

As you've discovered, the :first selector matches the first element of the selector you apply it to, and will only return (at most) one element.

You need to use the :first-child selector, which will match any element that is the first child of its parent. (Note that if there is a different element before the first p, it still won't work)

SLaks
What do you mean?
SLaks
I realize that; that's what I meant by the parenthetical in my second paragraph.
SLaks