1

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>
amirdaraee
  • 79
  • 1
  • 8

2 Answers2

2

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>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

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>
brk
  • 48,835
  • 10
  • 56
  • 78