'Create div element in JavaScript and add as parent of another div which was already exist in html file using pure vanilla JavaScript [duplicate]
Right now my .html file like this:
<body>
<h2 id="h2">Child</h2>
</body>
Here I want to make a parent div Element of #h2. Here I cannot replace body element... I want to create a parent div of h2 element like:-
I want my html file like this using vanilla JavaScript.
<body>
<div id="parent">
<h2 id="h2">Child</h2>
</div>
</body>
Solution 1:[1]
Something like this should do the trick: create the parent element, append it in the body, and move (append) the h2 into the parent element.
var parentEl = document.createElement("div")
parentEl.setAttribute("id", "parent")
document.body.appendChild(parentEl)
parentEl.append(document.getElementById("h2"))
<body>
<h2 id="h2">Child</h2>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ionică Bizău |
