Ghasem
Ghasem

Reputation: 15563

Add css style to all elements with specific class in jQuery

I have some lists in my page which are the same

<ul class="tabItem">
    <li class="active">
        <hr>
        <a href="#tab-1">tab1</a>
        <hr>
    </li>
    <li>
        <hr>
        <a href="#tab-2">tab2</a>
        <hr>
    </li>
    ...
</ul>

How can I add css to all <ul>tags with .tabItem class at the whole page using jQuery?

Currently I'm doing this, which works only on the first <li> childs

$(".tabItem li").children('hr').eq(0).css({"transform": "translateY(-12px)"});
$(".tabItem li").children('hr').eq(1).css({"transform": "translateY(12px)"});

Upvotes: 3

Views: 11061

Answers (4)

JBA
JBA

Reputation: 2899

$("ul.tabItem").addClass("yourClass");

With this, you can add a class to all of the elements that have the class tabItem already. In your class you can add all the styles that you need to provide, which is usually a better practice than just assigning it to the element itself.

If you still want to assign the styles directly, take a look at the css method in jQuery.

Upvotes: 0

Alex Olkhovskii
Alex Olkhovskii

Reputation: 136

$('ul.tabItem').css({"transform": "translateY(-12px)"});

or for hr tag

$('ul.tabItem hr').css({"transform": "translateY(-12px)"});

Upvotes: 2

Chris Pietschmann
Chris Pietschmann

Reputation: 29885

Here's all ul tags with .tabItem class:

$('ul.tabItem').css({ });

Here's the child action you're attempting:

$('ul.tabItem li hr:first-child').css({"transform": "translateY(-12px)"});
$('ul.tabItem li hr:last-child').css({"transform": "translateY(12px)"});

Although just using CSS would be better:

ul.tabItem li hr:first-child {
    transform: translate(-12px);
}
ul.tabItem li hr:last-child {
    transform: translate(12px);
}

Using CSS method then there's no JavaScript necessary.

Upvotes: 6

Pedro Estrada
Pedro Estrada

Reputation: 56

you can do this with just css no need to use jquery

like so:

<style>
.tabItem hr {
    transform: translateY(-12px)
}
</style>

Upvotes: 0

Related Questions