hfarazm hfarazm - 6 months ago 11
jQuery Question

Add class to ALL matching parent div

ok this seems simple but I am not able to solve it for some hours.

Following are four div.testName, what I want is:
if div.testName contains child div#wrong then it must add class 'wrongParent' to that specific parent.
Similarly, if div.testName contains child div#right then it must add class 'rightParent' to that specific parent.

Now if there are 3 div#wrong then 3 div.testName must also have 3 wrongParent assigned to them one for each div.

I have created fiddle here: https://jsfiddle.net/farazi482/aLd9w97s/6/

Please help

<div class="testName">
<div class="head">
<h3>wrong heading</h3>
</div>
<div id="wrong">
</div>
</div>

<div class="testName">
<div class="head">
<h3>wrong heading</h3>
</div>
<div id="wrong">
</div>
</div>

<div class="testName">
<div class="head">
<h3>right heading</h3>
</div>
<div id="right">
</div>
</div>
<div class="testName">
<div class="head">
<h3>right heading</h3>
</div>
<div id="right">
</div>
</div>


I am using this jquery:

$( "#right" ).each(function( ) {
$(this).parent().addClass('rightParent');
$('<span>i m right</span>').insertBefore('.testName .head > h3');
});

$( "#wrong" ).each(function( ) {
$(this).parent().addClass('wrongParent');
$('<span>i m wrong</span>').insertBefore('.testName .head > h3');
});

Answer

Change your id to class

$( ".right" ).each(function( ) {
	$(this).parent().addClass('rightParent');
	$('<span>i m right</span>').insertBefore('.testName .head > h3');
});
			
$( ".wrong" ).each(function( ) {
	$(this).parent().addClass('wrongParent');
	$('<span>i m wrong</span>').insertBefore('.testName .head > h3');
});
.testName { 
  width:90%;
  float: left;
  margin: 10px;
  border: solid 4px grey;
}
.rightParent {
  border: solid 4px green;
}
.wrongParent {
  border: solid 4px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="testName">
    <div class="head">
      <h3>wrong heading</h3>
    </div>
    <div class="wrong">
    </div>
 </div>
 
 <div class="testName">
    <div class="head">
      <h3>wrong heading</h3>
    </div>
    <div class="wrong">
    </div>
 </div>
 
  <div class="testName">
    <div class="head">
      <h3>right heading</h3>
    </div>
    <div class="right">
    </div>
 </div>
 
 <div class="testName">
    <div class="head">
      <h3>right heading</h3>
    </div>
    <div class="right">
    </div>
 </div>
 
 

Comments