简体   繁体   中英

How to add and remove class dynamically to child div based on value in Jquery

if data value is matching with any div inside requestsampler class then dynamically add new class(sampleClass) to test class inside the matching container

js:

var data = **somevalue**;

data is dynamic value

html:

<div class="requestsampler">
  <div class= "**somevalue**">
    <div class="test">  // add new class <div class="test sample class">
     //
    </div>
    
  </div>
   <div class= "somevalue2">
     <div class="test">
      //
    </div>
    
  </div>
   <div class= "somevalue3">
     <div class="test">
      //
    </div>
    
  </div>
</div>

tried not working:

$('.requestsampler').hasClass(data) {
  $(.'requestsampler .`${data}` .test').addClass('sampleclass');
}

You could simply use Attribute Contains Prefix Selector [name|="value"] for more info please refer http://jqapi.com/#p=attribute-contains-prefix-selector. . below is the code for your example.

 $(document).ready(()=>{ var data = "somevalue"; $('div[class|="'+data+'"]>.test').addClass("sampleclass"); })
 .sampleclass{ background-color:red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="requestsampler"> <div class= "somevalue"> <div class="test"> // add new class <div class="test sample class"> // </div> </div> <div class= "somevalue2"> <div class="test"> // </div> </div> <div class= "somevalue3"> <div class="test"> // </div> </div> </div>

you could try jquery elem.find() api. And also use className with string and numeric combination instead of symbols

i have changed the condition with element find length. Because hasClass() only perform on the selector element. So if you are using find() they will find the matched element.

And also your if condition does not make any sense, without condition is also working same

Updated

If you need first test element. use .eq(0) or else use different className for the first test element

 var data = "somevalue"; if ($('.requestsampler').find(`.${data}`).length > 0) { $('.requestsampler').find(`.${data}`).find('.test').eq(0).addClass('sampleclass'); }
 .sampleclass { background: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="requestsampler"> <div class="somevalue"> <div class="test"> // add new class <div class="test sample class"> sample </div> </div> <div class="somevalue2"> <div class="test"> // </div> </div> <div class="somevalue3"> <div class="test"> // </div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM