Is there a way to use Jquery's .unwrap()
multiple times without copying and pasting? It'd be nice if it could accept an argument or something like: .unwrap(4)
but it doesn't. Is there a more clever solution to achieving the following:?
$(".foo a").unwrap().unwrap().unwrap().unwrap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="foo">
<div>
<ul>
<li>
<div>
<a href="#">Link 1</a>
</div>
</li>
</ul>
</div>
</li>
<li class="foo">
<div>
<ul>
<li>
<div>
<a href="#">Link 2</a>
</div>
</li>
</ul>
</div>
</li>
<li class="foo">
<div>
<ul>
<li>
<div>
<a href="#">Link 3</a>
</div>
</li>
</ul>
</div>
</li>
</ul>
To wrap html control, use the wrap() method and unwrap() method to unwrap html control.
unwrap() method removes the element's parent and returns the unwrapped content. This is effectively the inverse of the . wrap() method. The matched elements (and their siblings, if any) replace their parents within the DOM structure.
The unwrap() method is an inbuilt method in jQuery which is used to remove the parent element from the selected element.
Use parentsUntil
the child of foo (.foo > *
)
(which would be an ancestor of the element).
Use addBack
to include the element itself.
$('.foo a').parentsUntil('.foo > *').addBack().unwrap();
Fiddle 1
n
times, this does it:
$.fn.unwrapN = function(n) {
while(n--) $(this).unwrap();
return $(this);
}
Fiddle 2
You could always write your own:
$.fn.unwrapTimes = function(times){
var unwrapCount = times;
return this.each(function(){
var $this = $(this);
for(var i=0;i<unwrapCount;i++){
$this.unwrap();
}
});
};
fiddle
Obviously the name should be changed but the logic is sound.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With