user3699344
user3699344

Reputation: 93

wrap anchor tag around parent element

I have a div with anchor tag inside it. I need to wrap the entire div with anchor tag with the same href as in child div using jQuery.

<div class="parent-div">
  <div class="child-div">
     <h3><a href="example.com">MORE INFORMATION</a></h3>
  </div>
</div>

Expected output:

<a href="example.com" target="_blank">
<div class="parent-div">
  <div class="child-div">
     <h3><a href="example.com">MORE INFORMATION</a></h3>
  </div>
</div>
</a>               

Upvotes: 1

Views: 880

Answers (2)

Hassan Sadeghi
Hassan Sadeghi

Reputation: 1326

Try this if you don't want to use wrap function and you want to use common jQuery functions:

;(function(p){
    $("<a target='_blank' href='"+p.find("a").attr("href")+"'></a>").insertBefore(p).append(p);
})($(".parent-div"));

But nested anchor is not valid. For solve this problem you can update above code similar this:

 ;(function(p){
    var a=p.find("a");
    $("<a target='_blank' href='"+a.attr("href")+"'></a>").insertBefore(p).append(p);
    $("span").insertBefore(a).html(a.html());
    a.remove();
  })($(".parent-div"));

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You can use .wrap() function as shown below For More Information on Wrap

$(function(){
  var $anchor = $('div.parent-div a').clone();//clone existing anchor
  $anchor.text('');//remove text
  $anchor.attr('target','_blank');
  $('div.parent-div').wrap($anchor);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent-div">
  <div class="child-div">
     <h3><a href="example.com">MORE INFORMATION</a></h3>
  </div>
</div>

Upvotes: 0

Related Questions