Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add class to closest ul

I'm trying to add a class to the following < ul > for a h3-element which contains the string "Informationen".

That's how the html-output looks like now:

<h3>Informationen</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit</li>
<li>Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes</li>
<li>Donec quam felis, ultricies nec, pellentesque eu</li>
</ul>

I want to achieve the code is like this:

<h3>Informationen</h3>
<ul class"normal">
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit</li>
<li>Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes</li>
<li>Donec quam felis, ultricies nec, pellentesque eu</li>
</ul>

I have several h3-elements with different strings, so I'm grabbing the correct one with this script:

$('h3').each(function() {
    var $this = $(this);
    var text = $this.html();
    if (text == 'Informationen'){
    alert(text);
    };
});

Now the alert shows me the string "Informationen" when an Element with this text/string is found.

To now add a class to the closest/next ul I tried this:

$('h3').each(function() {
    var $this = $(this);
    var text = $this.html();
    if (text == 'Informationen'){
    //alert(text);
    $this.closest('ul').addClass('normal');
    };
});

But this didn't work, like the following script didn't work too:

$('h3').each(function() {
    var $this = $(this);
    var text = $this.html();
    if (text == 'Informationen'){
    //alert(text);
    $(this).closest('ul').addClass('normal');
    };
});

Here's a fiddle for this: http://jsfiddle.net/JNtw2/1/

Can anyone point me to a solution for this?

like image 430
EM Em Avatar asked Dec 01 '25 20:12

EM Em


1 Answers

closest() gets the closest matching parent element, you're looking for next() as the UL comes right after the H3

$('h3').each(function() {
    var $this = $(this);
    var text = $this.html();
    if (text == 'Informationen'){

        $this.next('ul').addClass('normal');

    };
});

FIDDLE

like image 149
adeneo Avatar answered Dec 03 '25 09:12

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!