为何JS创建<section>后querySelectorAll返回长度为3而非4?
为什么用document.createElement创建的未被querySelectorAll检测到?
问题描述
我的HTML文件里原本有3个<section>标签,通过JavaScript创建了一个新的<section>元素:
const lastSection = document.createElement('section');
随后用以下代码获取所有<section>元素:
const allSections = document.querySelectorAll('section');
但运行console.log(allSections.length);返回结果是3,而我预期是4,想知道原因。
解答
document.createElement('section')只是在内存中创建了一个
querySelectorAll('section')的作用是查找已经挂载到DOM树上的所有
如果想要这个新创建的
// 示例:追加到body末尾 document.body.appendChild(lastSection); // 或者追加到某个指定父元素 const parent = document.querySelector('#some-parent'); parent.appendChild(lastSection);
执行上述代码后,再调用querySelectorAll('section')就能得到长度为4的结果了。
内容的提问来源于stack exchange,提问作者ProSystem101
相关产品推荐
相关产品推荐

