Where in the HTML node tree are dynamically generated elements stored?

Viewed 177

I dynamically create an element using the following line of code in JavaScript:

const element = document.createElement("img");

I am able to access and modify the properties of the element, so it clearly exists, but what I can't figure out is where it is stored in the HTML node tree.

element.parentNode and element.previousSibling both return null. Does anyone know where it is actually located?

1 Answers

When creating an element using document.createElement(), the element is only stored within memory and not accessessable with element.children, or similar methods/getters.

To actually get access to it, you need to append it to an element in the DOM tree. Using one of many of the DOM methods:

Once done, you can then access the element as you normally would. With one of the many accessors element.children, element.querySelector(), etc.

You can however access items that haven't been inserted into the dom as long as you have reference to them. As you can see here the div never gets inserted, however, I can still access the child span from the div, but I can not access the div from the say the documentElement because it hasn't been added to the documentElement.

let div = document.createElement('div')
let span = document.createElement('span')

div.appendChild(span)

// We can access the child from the div
// Since the span has been added to the div
// Returns "SPAN"
console.log(div.firstChild.tagName)

// We can not access the div from the document
// Since the div wasn't added to the document
// Returns "null"
console.log(document.querySelector('div'))

Related