Viktor Koncsek Viktor Koncsek - 5 months ago 12
Javascript Question

How to apply class to container that's children have the required two class?

Hard to explain, but here is an example:

<div>
<span class='first'>text</span>
<span>text</span>
</div>

<div>
<span>text</span>
<span class='second'>text</span>
</div>

<div>
<span class='first'>text</span>
<span class='second'>text</span>
</div>


I want to apply a class to the div, that has both
first
and
second
classed childs.

So this would be the modified html:

<div>
<span class='first'>text</span>
<span>text</span>
</div>

<div>
<span>text</span>
<span class='second'>text</span>
</div>

<div class='addedClass'>
<span class='first'>text</span>
<span class='second'>text</span>
</div>


I could make it by labelling divs with
data
attributes, but that doesn't seems the best way, I believe there is a way with jquery's engine.

Answer

You could try chaining your jQuery selectors like so:

$("div").has(".first").has(".second").addClass("addedClass");

So essentially you're saying, select the div that has a child element with class "first" as well as one with class "second".

Example: http://codepen.io/JasonGraham/pen/xOdRpz