Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you .unwrap() an element multiple times?

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>
like image 612
Lei-Lonnie Avatar asked May 07 '15 22:05

Lei-Lonnie


People also ask

How do I unwrap HTML?

To wrap html control, use the wrap() method and unwrap() method to unwrap html control.

What is the use of unwrap method?

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.

Which of the following is a valid function that is used to unwrap elements?

The unwrap() method is an inbuilt method in jQuery which is used to remove the parent element from the selected element.


2 Answers

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


If you want a generic function that unwraps an object n times, this does it:
$.fn.unwrapN = function(n) {
  while(n--) $(this).unwrap();
  return $(this);
}

Fiddle 2

like image 58
Rick Hitchcock Avatar answered Sep 28 '22 02:09

Rick Hitchcock


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.

like image 24
dbarnes Avatar answered Sep 28 '22 04:09

dbarnes