0

I am trying to wrap a DOM element to new element one I create. But not works.

function moveToLink(){
        var button = document.getElementById('button');
        var link = document.createElement('a');
        link.setAttribute('href', '#');
        
        link.appendChild( button); // need wrap
     
      }
      
      moveToLink();
a{
  border:2px solid gray;
  display:block;
}
<input type="button" id="button" value="try me" onclick="moveToLink()">

Live Demo

vahdet
  • 6,357
  • 9
  • 51
  • 106
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

1

First of all, you have to append the "link" element to a part of the document. After that clicking on that link appends the button to "link".

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script> 
      function moveToLink(){
        var button = document.getElementById('button');
        var link = document.createElement('a');
        link.setAttribute('href', '#');
        document.body.appendChild(link);
        link.appendChild( button);
      }
    </script>
</head>
<body>
    <input type="button" id="button" value="try me" onclick="moveToLink()" />
</body>
</html>
Saeed
  • 2,169
  • 2
  • 13
  • 29
  • add the js part of the code in a script tag like my code: – Saeed Jul 04 '18 at 13:03
  • upvoted just because you are new, using SO with very low rep is very frustrating. The code you gave creates invalid html ( inside tag), but that's what OP wanted, not your fault. – Braca Jul 04 '18 at 13:24
1

You don't append link itself to body.

Edit: Changed code to replace element instead of append, it wasn't what you wanted. And it doesn't work with link because it can't wrap input. check here

function moveToLink(){
    var button = document.getElementById('button');
    var div = document.createElement('div');
    document.getElementsByClassName('parent')[0].replaceChild(div, button);
    div.appendChild( button);
}
Hikmat G.
  • 2,591
  • 1
  • 20
  • 40