Managing packaging and deployment methods in jQuery

I am working on the demo code below. How can I use jQuery in these ways ?:

1- Wrap p only if it is not already wrapped in .check-wrap-sapn

and

2- Expand only .check-wrap-sapn and not other parents?

What is happening now, jQuery wraps the p element in .check-wrap-sapn until the user presses #wrap and removes all p parents, even if there is no wrapper named .check-wrap-sapn

 $("#wrap").on("click", function() { $("p").wrap("<div class='check-wrap-sapn'></div>"); }); $("#unwrap").on("click", function() { $("p").unwrap("<div class='check-wrap-sapn'></div>"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="container"> <div class="well"> <p>This is for Wrapping</p> </div> </div> <button class="btn btn-default" id="wrap">Wrap</button> <button class="btn btn-default" id="unwrap">Un Wrap</button> 

+6
source share
1 answer

Get it with parent() and check it .check-wrap-sapn or not use is()

 var $p = $("p"); $("#wrap").on("click", function() { if ($p.parent().is(':not(.check-wrap-sapn)')) $p.wrap("<div class='check-wrap-sapn'></div>"); }); $("#unwrap").on("click", function() { if ($p.parent().is('.check-wrap-sapn')) $p.unwrap("<div class='check-wrap-sapn'></div>"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="container"> <div class="well"> <p>This is for Wrapping</p> </div> </div> <button class="btn btn-default" id="wrap">Wrap</button> <button class="btn btn-default" id="unwrap">Un Wrap</button> 
+5
source

All Articles