我使用JavaScript中的以下代码行动态创建元素:
const element = document.createElement("img");
我能够访问和修改元素的属性,因此它显然存在,但是我不知道是它在HTML节点树中的存储位置。
element.parentNode
和element.previousSibling
都返回null
。有人知道它的实际位置吗?
答案 0 :(得分:5)
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'))