Stefanija
Stefanija

Reputation: 1418

Ordered List with jQuery

How can I add css class in (* this *) li-s with jQuery?

<ul>
    <li>*this*</li>
<ol>
    <li></li>
     <li></li>
</ol>
    <li>*this*</li>
<ol>
    <li></li>
     <li></li>
</ol>
</ul>

Upvotes: 0

Views: 35

Answers (3)

Ykaro Lemes
Ykaro Lemes

Reputation: 97

You can use this.

$('ul > li').addClass('className');

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

Assuming proper valid structure is :

<ul>
    <li>*this*
        <ol>
            <li></li>
            <li></li>
        </ol>
    </li>
    <li>*this*
        <ol>
            <li></li>
            <li></li>
        </ol>
    </li>
</ul>

Then you can use:

$('ul').children().addClass('someClass');

You should give the <ul> a class or id for more specific targeting of the selector so as to not affect any other <ul> in page also

Upvotes: 0

Jesse
Jesse

Reputation: 1262

Loop through the elements, and check the text attribute:

fiddle: https://jsfiddle.net/yftaLtxr/1/

var els = $('li');
console.log(els);

for(var i = 0; i < els.length; i++)
{
    var li = $(els[i]);

    var text = li.text();
    if(text == "*this*")
    {
        li.addClass("test");
    }
    console.log(li.attr('class'));
}

Upvotes: -1

Related Questions