Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery / CSS – addClass to first:p of multiple div with specified class

Tags:

html

jquery

css

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!

like image 774
HandiworkNYC.com Avatar asked Apr 18 '10 13:04

HandiworkNYC.com


People also ask

Can we add more than one CSS classes to the selected elements using the addClass () method?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

Can you add multiple classes to an element jQuery?

Approach: First select the element to which multiple classes will be added. Then use addClass() method to add multiple classes to the element and removeClass() method to remove multiple classes.


1 Answers

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("...");
  });
});
like image 165
cletus Avatar answered Oct 13 '22 20:10

cletus