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?
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 ul
s 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>
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With