Jarco
Jarco

Reputation: 1765

adding classes to children

When I do $('ul.latestnews ul li').parent().prev().text()); I get back the content of the targeted li. (word1 or word2 in this example).

But when I do

$('ul.latestnews ul li').addClass($(this).parent().prev().text());

It doesn't add the class. When I do a console.log on that last statement it just returns all the li's I am trying to add the class to.

What I am trying to do is this:

<ul class="latestnews">
    <li>word1</li>
    <ul>
        <li>my class should become word1</li>
        <li>my class should become word1</li>
    </ul>
    <li>word2</li>
    <ul>
        <li>my class must become word2</li>
    </ul>        
</ul>

Where did I go wrong?

Upvotes: 0

Views: 54

Answers (2)

gdoron
gdoron

Reputation: 150253

this is the DOM element only inside of a jQuery function, like each:

$('ul.latestnews ul li').each(function(){
    $(this).addClass($(this).parent().prev().text());
});

Live DEMO this in your code is probably the Window object...

Note that those kind of DOM traversal with prev, parent can break very easily if you change the DOM structure a bit, you might want to use other selector based of the elements classes.

Upvotes: 2

Taha Paksu
Taha Paksu

Reputation: 15616

I think the html code is not quite right as it should be like :

<ul class="latestnews">
    <li>word1</li>
    <li>
        <ul>
            <li>my class should become word1</li>
            <li>my class should become word1</li>
        </ul>
    </li>
    <li>word2</li>
    <li>
        <ul>
            <li>my class must become word2</li>
        </ul>
    </li>        
</ul>

then:

$("ul.latestnews ul > li").each(function(){
    var $this=$(this);
    var className = $this.parents("li").first().prev().text();
    $this.addClass(className);
});

Upvotes: 1

Related Questions