If I create a element using document.createElement()
, what is its parent? Is it body? Sorry for such a basic question but I've tried using JavaScript to find the parent and it returns an object, not really sure about this one.
Thanks
If I create a element using document.createElement()
, what is its parent? Is it body? Sorry for such a basic question but I've tried using JavaScript to find the parent and it returns an object, not really sure about this one.
Thanks
Share Improve this question edited Jul 27, 2013 at 10:58 putvande 15.2k3 gold badges36 silver badges51 bronze badges asked Jul 27, 2013 at 10:41 jskidd3jskidd3 4,80315 gold badges68 silver badges132 bronze badges2 Answers
Reset to default 5The element is created in memory and does not have any parent (yet).
When you place the element in the DOM using appendChild()
or similar methods, it will have a parent.
JavaScript will return null
if you try to access an element that doesn’t exist, and that includes parents to elements that only exist in memory.
To access the element, assign it to a variable, f.ex:
var elem = document.createElement('div'); // elem is now the element reference
You don’t need to explicitly delete elements that you haven’t appended to the DOM as they only exist in memory and will be wiped out once they are no longer referenced.
Until you attach it to something, it is nothing (null
).
> x = document.createElement("div");
<div></div>
> x.parentNode
null
> document.body.appendChild(x);
<div></div>
> x.parentNode
<body></body>
With regards to your ment, given an array of elements [x, y, z]
, which may or not be inserted into the DOM, you can remove those in the DOM as follows;
var els = [x, y, z];
for (var i=0;i<els.length;i++) {
if (els[i].parentNode) {
els[i].parentNode.removeChild(els[i]);
}
}
... as only elements in the DOM will have a truthy parentNode
.