简体   繁体   中英

Cannot add class to element children

I'm trying to find an element in my HTML file based on its parent class name and then add a class to it. I've tried the solution in here but it won't work. also, I've tried to log the child class name to see if it's working but it will return undefined . My HTML file is something like this:

 $(document).ready(function () { console.log($(".grid-container").find(">:first-child").className); $(".grid-container").find(">:first-child").toggleClass("search-controller"); }); 
 .search-controller { height: 100%; color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div ui-view="" class="grid-container ng-scope" style=""> <div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope"> This is test data </div> </div> 

To get the class name from jQuery object you have to use prop() . Try to set some style to the element so that the changes are visible (like color ):

 $(document).ready(function () { console.log($(".grid-container").find(">:first-child").prop('class')); $(".grid-container").find(">:first-child").toggleClass("search-controller"); }); 
 .search-controller { height: 100%; color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div ui-view="" class="grid-container ng-scope" style=""> <div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope"> This is test data </div> </div> 

Use addClass instead of toggleClass . toggleClass class will require an event like click to toggle the class.

 $(document).ready(function() { //console.log($(".grid-container").find(">:first-child").className); $(".grid-container").find(">:first-child").addClass("search-controller"); }); 
 .search-controller { height: 100%; border: 1px solid green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div ui-view="" class="grid-container ng-scope" style=""> <div ng-controller="citySearchController" ng-init="initialize()" class="ng-scope">Test </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