0

How to create parent of child element in javascript?

Hello everyone! Please help me how can I create parent node of an element without replacing its parent element.

30th May 2021, 5:20 AM
Coder-Rohit[{(∞)}]
Coder-Rohit[{(∞)}] - avatar
14 Respostas
+ 3
div.appendChild(h2)
30th May 2021, 6:47 AM
visph
visph - avatar
+ 2
mmhh... in html (dom) tree context, a node has only one parent... you cannot "create parent node of an element without replacing its parent element" ;P what are you trying to achieve exactly? what you could do is create a element (all elements are nodes, while some nodes are not elements) wich can be used as parent of another node/element, even if the last one had another element as parent... but so the child will have its parent element replaced, without removing the parent from the dom ^^
30th May 2021, 5:35 AM
visph
visph - avatar
+ 2
sure. if div hold reference of the created div and h2 hold reference of your targeted h2... as one element could have only one parent, making it child of another one automatically remove it from its initial parent if he has one
30th May 2021, 6:50 AM
visph
visph - avatar
+ 2
that's just what I've said in my first post ^^
30th May 2021, 6:53 AM
visph
visph - avatar
+ 1
I do not understand, and that's why I was asking what you try to achieve... so, now that your problem is clearly explained: you create a div element, wich you append/insert to body, then you could move the h2 child of body to be child of div... or even before inserting the new div parent of h2: it doesn't matter ^^
30th May 2021, 6:42 AM
visph
visph - avatar
+ 1
Maybe create parent div, place it before/after h2, take h2 and put it as child of div?
30th May 2021, 6:44 AM
Lisa
Lisa - avatar
+ 1
Coder-Rohit[{(∞)}] try it and see if it works for you
30th May 2021, 6:49 AM
Lisa
Lisa - avatar
+ 1
Thank you visph & Lisa
30th May 2021, 6:59 AM
Coder-Rohit[{(∞)}]
Coder-Rohit[{(∞)}] - avatar
0
visph You are not understanding, Here is examples condition:- <body> <h2 id="h2">Child</h2> </body> Here I want to make a parent divElement of #h2. Here I cannot replace body element... I want to create a parent div of h2 element like:- <body> <div> <h2 id="h2">Child</h2> </div> </body>
30th May 2021, 6:39 AM
Coder-Rohit[{(∞)}]
Coder-Rohit[{(∞)}] - avatar
0
visph I want to create parent div element of h2 element using DOM
30th May 2021, 6:44 AM
Coder-Rohit[{(∞)}]
Coder-Rohit[{(∞)}] - avatar
0
Lisa How can I move h2 element to div element
30th May 2021, 6:45 AM
Coder-Rohit[{(∞)}]
Coder-Rohit[{(∞)}] - avatar
0
visph Will it work
30th May 2021, 6:48 AM
Coder-Rohit[{(∞)}]
Coder-Rohit[{(∞)}] - avatar
0
Ok
30th May 2021, 6:50 AM
Coder-Rohit[{(∞)}]
Coder-Rohit[{(∞)}] - avatar
0
Wow! It works
30th May 2021, 6:58 AM
Coder-Rohit[{(∞)}]
Coder-Rohit[{(∞)}] - avatar