Sooraj Chandran Sooraj Chandran - 6 months ago 21
CSS Question

Using Jquery wrap function with absolute placed element

I'm trying to use jQuery

wrap
function on an element which is positioned
absolute
. Following is my code.

On clicking the child element I'm wrapping the same with another div , but its not working. Instead the wrapper element appears on the top of the screen. How can I manipulate
css
or
js
to wrap the child element.



$(document).ready(function() {
$("#child").click(function() {
$(this).wrap("<div class='wrapper'></div>")
});
});

#container {
position: relative;
height: 500px;
width: 600px;
background: #ccc
}
#child {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background: #444;
border: 2px solid red;
height: 200px;
width: 200px;
}
.wrapper {
border: 1px dashed green;
}

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

</div>
</div>




Answer

Just update the wrapper class

$(document).ready(function() {
  $("#child").click(function() {
    $(this).wrap("<div class='wrapper'></div>")
  });
});
#container {
  position: relative;
  height: 500px;
  width: 600px;
  background: #ccc
}
#child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  background: #444;
  border: 2px solid red;
  height: 200px;
  width: 200px;
}
.wrapper {
  border: 1px dashed green;
  height: 200px;
  width: 200px;
  position:absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
   margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="container">
  <div id="child">

  </div>
</div>

Comments