1

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?

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this will add the class to the div with the class row, hence the multiple colored lines here
2

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.

1 Comment

Thank you, great alternative

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.