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.
14 odpowiedzi
+ 3
div.appendChild(h2)
+ 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 ^^
+ 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
+ 2
that's just what I've said in my first post ^^
+ 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 ^^
+ 1
Maybe create parent div, place it before/after h2, take h2 and put it as child of div?
+ 1
Coder-Rohit[{(∞)}] try it and see if it works for you
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>
0
visph
I want to create parent div element of h2 element using DOM
0
Lisa
How can I move h2 element to div element
0
visph
Will it work
0
Ok
0
Wow! It works