hfarazm
hfarazm

Reputation: 1417

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

Please help

$( "#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');
});
<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>

Upvotes: 0

Views: 74

Answers (1)

Garvit Mangal
Garvit Mangal

Reputation: 900

Change your id to class

$( ".right" ).each(function( ) {
	$(this).parent().addClass('rightParent');
	$('<span>i m right</span>').insertBefore($(this).prev());
});
			
$( ".wrong" ).each(function( ) {
	$(this).parent().addClass('wrongParent');
	$('<span>i m wrong</span>').insertBefore($(this).prev());
});
.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>

Upvotes: 1

Related Questions