7

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>
Pang
  • 9,564
  • 146
  • 81
  • 122
hallibus
  • 245
  • 1
  • 4
  • 10
  • 4
    possible duplicate of [Wrapping a set of DOM elements using JavaScript](http://stackoverflow.com/questions/3337587/wrapping-a-set-of-dom-elements-using-javascript) – ᔕᖺᘎᕊ Jul 17 '15 at 09:42
  • jQuery IS javascript so you don't need jQuery at all. – Rob Jul 18 '15 at 02:43

1 Answers1

11

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()">
jasonscript
  • 6,039
  • 3
  • 28
  • 43