我使用JavaScript中的以下代码行动态创建元素:
const element = document.createElement("img");
Run Code Online (Sandbox Code Playgroud)
我能够访问和修改元素的属性,所以它显然存在,但我无法弄清楚它是存储在HTML节点树中的位置.
element.parentNode和element.previousSibling都返回null.有谁知道它实际位于何处?
使用document.createElement()创建元素时,该元素仅存储在内存中,不能与element.children类似的方法/ getter 一起访问.
要实际访问它,您需要将它附加到DOM树中的元素.使用许多DOM方法之一:
完成后,您可以像往常一样访问元素.随着许多存取之一element.children,element.querySelector()等等.
但是,只要您参考了dom,就可以访问尚未插入dom的项目.正如你可以在这里看到的div永远不会被插入的,但是,我仍然可以访问孩子span从div,但我不能访问div从说,documentElement因为它没有被添加到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'))Run Code Online (Sandbox Code Playgroud)