换行<a> around </a> <div> <a> without jQuery

时间:2015-07-17 09:36:45

标签: javascript jquery html

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>

1 个答案:

答案 0 :(得分:3)

您可以创建新的link元素,将DIV的HTML复制到链接中,然后使用insertBefore

将链接元素插入DOM

&#13;
&#13;
  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();
  }
&#13;
<div id="wrapMe">Some content in a div</div>
<input type="button" value="try me" onclick="moveToLink()">
&#13;
&#13;
&#13;