Francois M Francois M - 9 days ago 5
jQuery Question

Detect a special class during a each into jQuery

How can I check if all my

span
elements has a special class (a, b or c) ?

<form id="form">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<span class="a b"><span>
<span class="b"><span>
<span class="b c"><span>
<span class="a c"><span>
<span class="c"><span>
</div>
</div>
</form>

<script>
var class_to_search = 'a';
$('#form > span:not(.'+ class_to_search +')').each( function(i) {
$(this).addClass('hide');
});
</script>


But it doesn't work.

Could you please help me please ?

Thanks.

Answer

All you need to do is when you determine which class you want to show - hide all elements (spans) and then showthe ones that have that class.

$(document).ready(function(){
  $("#selection").change(function(){
    var elementToShow = $(this).val();
    $('#contentRow span').hide();
    $('#contentRow .' + elementToShow).show();
   })
});
#contentRow span{display:block}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <label for = "selection">Select the element you wish to show</label>
  <select id = "selection">
     <option selected disabled></option>
     <option>a</option>
     <option>b</option>
     <option>c</option>
  </select>

  <hr/>

   <div class="row">
        <div id= "contentRow" class="col-md-10 col-md-offset-1">
            <span class="a b">test 1 (contains classes a & b)</span>
            <span class="b">test 2 (contains class b)</span>
            <span class="b c">test 3 (contains classes b & c)</span>
            <span class="a c">test 4 (contains classes a & C)</span>
            <span class="c">test 5 (contains class c)</span>
        </div>
    </div>
</form>