Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling wrap and unwrap methods in jQuery

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

1- Wrap the p only if it has not already wrapped with .check-wrap-sapn

and

2- Unwrap only .check-wrap-sapn and not any other parent?

What is happening now jQuery wraps the p element with .check-wrap-sapn as long as users clicks on #wrap and removes all parents of p even if there is not any wrapper called .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>
like image 533
Mona Coder Avatar asked Sep 25 '15 07:09

Mona Coder


People also ask

What is wrap and unwrap in jQuery?

createElement() to create an element, and wrap it around each selected element. Wrap elements using a function. Using a function to specify what to wrap around each selected element. Wrap and unwrap an element. How to toggle between wrapping and unwrapping an element.

What is wrap method in jQuery?

jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector).

What is wrap method?

WRAP stands for Widen Your Options, Reality-Test Your Assumptions, Attain Distance Before Deciding, and Prepare to Be Wrong. Widen Your Frame. One of the main pitfalls in decision making is having a narrow frame. That means you don't consider possible alternatives that might be better options.

What is the use of unwrap?

Definition and Usage The unwrap() method removes the parent element of the selected elements.


1 Answers

Get it's parent using parent() and check it's .check-wrap-sapn or not using 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>
like image 74
Pranav C Balan Avatar answered Oct 17 '22 16:10

Pranav C Balan