Lone Ray Lone Ray - 3 months ago 8
CSS Question

find class of a div after wrapping (.wrap) around a div class named "root"

I want to wrap a div (class "root") with a div (class "parent") around it. successfully wrapped, but when try to find that "parent" class with ".hasClass" function after wrapping around class "root", It returns me 'false'. Checkout this sample code. According to me, It has to be 'true'. where is the problem?



$(document).ready(function(){
$(".root").wrap("<div class='parent'></div>");
alert($(document).hasClass("parent"));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="root">123</div>




Answer

$(document).hasClass("parent") will check the presence of parent class on document element. It has no class named parent so it is returning false.

You should check for the length of jQuery object like $('.parent').length

$(document).ready(function() {
  $(".root").wrap("<div class='parent'></div>");
  alert($('.parent').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="root">123</div>