fightstarr20
fightstarr20

Reputation: 12628

jQuery add class to divs that contain element with class

I have a simple layout like this...

<div class="container">
    <div class="row" id="234">
        <div class="left special">
            This is left content
        </div>
        <div class="right">
            This is right content
        </div>
    </div>
    <div class="row" id="944">
        <div class="left">
            This is left content
        </div>
        <div class="right">
            This is right content
        </div>
    </div>
    <div class="row" id="332">
        <div class="left">
            This is left content
        </div>
        <div class="right special">
            This is right content
        </div>
    </div>
</div>

I am trying to use jQuery to target only the row ids that contain the special class within them. I have this so far

jQuery( ".row:has(.special)" ).addClass( "test" );

But it is not adding the test class, where am I going wrong?

Upvotes: 1

Views: 86

Answers (2)

Luca Kiebel
Luca Kiebel

Reputation: 10096

You can simply use the .has method here, to add a class to all elements that have an element with the class special in them:

$(".row").has(".special").addClass("test");
.test{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="row" id="234">
        <div class="left  special"> 
            This is left content special
        </div>
        <div class="right">
            This is right content
        </div>
    </div>
    <div class="row" id="944">
        <div class="left">
            This is left content
        </div>
        <div class="right">
            This is right content
        </div>
    </div>
    <div class="row" id="332">
        <div class="left">
            This is left content
        </div>
        <div class="right special">
            This is right content special
        </div>
    </div>
</div>

Upvotes: 3

Taplar
Taplar

Reputation: 24965

You could always go backwards.

$('.special').closest('.row').addClass('test');

Find the elements with the special class, find their closest parent record with the row class, and put the class on them. Since you are navigating from child to parent, you know that row has a child of special.

Upvotes: 2

Related Questions