Rob
Rob

Reputation: 6370

Find class, add class to parent (li)

I have some code that is generated by some Javascript (I don't want to adjust that, it's huge!). As a workaround, I can achieve what I want with Jquery and CSS, just not sure how to go about it.

I have several bullet points, I want to find all the span's with the class bubble-lorem, I then want to add a class to the parent li called price. I think Jquery does this but not sure how to achieve it.

The second part of the question, once it's added the class price to all the correct li's, I want to add a class clear to the next li after it. So for example if there was 3 <li class="price"> in a row, I want to find the next li after the last <li class="price"> and add a class to that?

<li>
    <span style="margin-left: 0px; width: 240px;" class="bubble bubble-default" data-duration="18"></span>
    <span class="date">01/2015-12/2016</span>
    <span class="label">Phase 1</span>
</li>

<li>
    <span style="margin-left: 30px; width: 30px;" class="bubble bubble-lorem" data-duration="2"></span>
    <span class="date">04/2015-06/2015</span>
    <span class="label">£0.8</span>
</li>

Upvotes: 0

Views: 738

Answers (5)

Rahul Munjal
Rahul Munjal

Reputation: 2693

Answer 1:

$("span.bubble-lorem").parent().addClass('price');

Answer 2:

$("li.price").next().addClass('clear');

Upvotes: 0

Qarib Haider
Qarib Haider

Reputation: 4906

For part one of your question:

// This finds all elements with 'bubble-lorem' class and 
// adds 'price' class to their parents
$( ".bubble-lorem" ).parent().addClass( "price" );

For second part of your question:

// This finds the elements with 'price' class whose next li does not have 
// 'price' class (which will be the last element) and adds 'clear' class to it
$('.price').next('li:not(.price)').addClass('clear');

Upvotes: 0

Roumelis George
Roumelis George

Reputation: 6746

Try this:

$('.bubble-lorem').parent('li').addClass('price');
$('.price').last().next().addClass('clear');

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

Part I: You need to use :has selector:

$('li:has(.bubble-lorem)').addClass('price');

Part II:

$('.price').next('li:not(.price)').addClass('clear');

Working Demo

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Both of your requests can be achieved with one-liners:

$('.bubble-lorem').closest('li').addClass('price');
$('.price').next('li:not(.price)').addClass('clear');

Upvotes: 2

Related Questions