wj R.
wj R.

Reputation: 359

How to add class to outer div which contains a particular inner class with jquery?

How to add class to "outer" if there is a div with class "inner"?

From

<div class="outer">
  <div class="inner>
   blah blah
  </div>
</div>

to

<div class="outer newclass">
  <div class="inner>
   blah blah
  </div>
</div>

Please help. thanks guys.

Upvotes: 1

Views: 2988

Answers (5)

PJT
PJT

Reputation: 21

$('.inner').closest('.outer').addClass('newclass');

Upvotes: 1

prajeesh
prajeesh

Reputation: 2382

if($('.outer div').hasClass('inner')) {
  $('.outer').addClass('new_class');
}

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

Solution 1: You need to use :has selector:

$('.outer:has(.inner)').addClass('newclass');

Solution 2: Or, find the inner element and add class to its parent element with class .outer:

$('.inner').closest('.outer').addClass('newclass');

Upvotes: 5

w33z33
w33z33

Reputation: 378

you can use the parent function of jquery

https://jsfiddle.net/bj7k3j0q/

$(document).ready(function () {
    $('.inner').parent(".outer").addClass("newClass");
});

Upvotes: 0

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

You can use .closest function. See below example :

$('.inner').closest('.outer').addClass('newclass');

Wherever you want to display output, its depend on your html structure and css definition. Then, the jquery selector will depend on that.

Upvotes: 0

Related Questions