One day, I came across a problem for unwrapping anchor tag from its contents.
Jquery provides us a unWrap function to unwrap the tag by removing it’s parent tag from the DOM.
Syntax:
1 | .unwrap() |
Note: it does not take any parameter
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <div> <a class="test" href="http://www.fellowtuts.com"> Best to learn here on fellow tuts <span> BEST NUMBER 1</span></a> </div> <script> $(function(){ $('.test').unwrap(); }) </script> Output: It will remove div tag which is parent of an anchor tag with class named test. |
But If we want to unwrap anchor text
1 2 3 4 5 6 7 | <script> $(function(){ // unwrapping anchor tag by maintaining its contents as it is $('.test').replaceWith(function(){ return $(this).html()}) // output // |
Its best to learn here BEST NUMBER 1
1 2 3 4 5 | // for unwrapping text of all the anchor tags class named with 'test' $('.test').replaceWith(function(){ return $(this).text()}) //output // |
Its best to learn here BEST NUMBER 1
1 2 3 4 5 | // if only one anchor tag exist with class named with 'test' $('.test').replaceWith($('.test').text()) //output // |
Its best to learn here BEST NUMBER 1
1 2 3 | }) </script> |
By Using unwrap function if any child tag exist in unwrapping tag
1 2 3 4 5 | $(function(){ $('.test span').unwrap(); // It will remove span parent anchor tag }) |
So there are lot of ways to unwrap a html tag itself using jQuery, overall it depends on your html structure.