Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add class to children - jquery

Tags:

html

jquery

I have this html code:

<div class="rotation">
  <ul>
    <li><img src="..." alt="" /></li>
    <li><img src="..." alt="" /></li>
    <li><img src="..." alt="" /></li>
  </ul>
</div>

I need to add class to ul, i want to do it using jquery, because ul, li are generated without any class.
Let say ul tag need to be <ul class="image_rotation">. How can i do it?

like image 822
miszczu Avatar asked Jul 05 '12 14:07

miszczu


2 Answers

Read about jQuery's addClass method here.

$('.rotation ul').addClass('image_rotation');

The above code will add a class of image_rotation to every ul that is a descendant of any element with the class rotation.

If you want to target only uls that are an immediate child of an element with a class of rotation, use the child selector (>):

$('.rotation > ul').addClass('image_rotation');

If you only want to do this on one .rotation element, you should give it an id and select it that way. For example:

$('#rotation ul');

and

<div id="rotation" class="rotation">
    <ul>
        <li><img src="..." alt="" /></li>
        <li><img src="..." alt="" /></li>
        <li><img src="..." alt="" /></li>
    </ul>
</div>
like image 137
lbstr Avatar answered Oct 20 '22 23:10

lbstr


I'd suggest keeping it simple:

$('div.rotation ul').addClass('image_rotation');

Or, if you have multiple ul elements within the div.rotation element, you can specify the first ul:

$('div.rotation ul:first').addClass('image_rotation');

The last ul:

$('div.rotation ul:last').addClass('image_rotation');

Or a ul of arbitray zero-based index, for example the third ul (with an index of 2):

$('div.rotation ul:eq(2)').addClass('image_rotation');

or:

$('div.rotation ul').eq(2).addClass('image_rotation');

Or an immediate child (so no ul elements nested in any other elements):

$('div.rotation > ul').addClass('image_rotation');

References:

  • addClass().
  • eq().
  • :eq selector.
  • :first selector.
  • :last selector.
like image 29
David Thomas Avatar answered Oct 20 '22 23:10

David Thomas