Amodio De Cicco
Amodio De Cicco

Reputation: 87

Show element having child element with specific CSS class

I have 2 hidden DIVs
every DIV contains a SPAN
I want to show only the DIV who has the SPAN with class RedBackground
The javascript code i wrote is not working

$("div span.RedBackground").show();
.greenBackground {
    color: green;
}

.RedBackground {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="display: none;">
<span  class="RedBackground">show this</span>
</div>

<div style="display: none;">
<span  class="GreenBackground">NOT show this</span>
</div>

Upvotes: 1

Views: 29

Answers (2)

eisbehr
eisbehr

Reputation: 12452

Use :has selector to get all div containing such element. Not need to use things like parent or closest:

$("div:has(span.RedBackground)").show();
.greenBackground { color: green; }
.RedBackground { color: red; }
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="display: none;">
  <span  class="RedBackground">show this</span>
</div>

<div style="display: none;">
  <span  class="GreenBackground">NOT show this</span>
</div>

Upvotes: 2

guradio
guradio

Reputation: 15565

  1. Selector is the other way around.
  2. use $("span.RedBackground").parent('div') to show div. means span.RedBackground's parent div which is hidden is shown
  3. your selector $("div span.RedBackground").show(); means div with span.RedBackground but the div is hidden so you cant still see any
  4. Commented below if there are other element between the span and the hidden div you can use closest("div")

$("span.RedBackground").parent('div').show();
.greenBackground {
    color: green;
}

.RedBackground {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="display: none;">
<span  class="RedBackground">show this</span>
</div>

<div style="display: none;">
<span  class="GreenBackground">NOT show this</span>
</div>

Upvotes: 0

Related Questions