Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap <a> around <div> without jQuery

I'm trying to wrap an <a> around a <div> without using jQuery since I don't want to embed the jQuery library. Is it possible with pure JavaScript?

The jQuery solution works great and looks like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("#mydiv").wrap("<a id='myanchor' href='#'></a>");
    });
</script>
like image 462
hallibus Avatar asked Jul 24 '26 22:07

hallibus


1 Answers

You can create a new link Element, copy the HTML of the DIV into the link and then insert the link element into the DOM using insertBefore

  function moveToLink(){
    var div = document.getElementById('wrapMe');
    
    var link = document.createElement('a');
    link.innerHTML = div.outerHTML;
    link.setAttribute('href', '#');
    
    div.parentNode.insertBefore(link, div);
    div.remove();
  }
<div id="wrapMe">Some content in a div</div>
<input type="button" value="try me" onclick="moveToLink()">
like image 156
jasonscript Avatar answered Jul 27 '26 11:07

jasonscript



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!