如何在<template>元素内查询元素?为何无法选中其中的<link>?
问题原因与解决方法
问题出在<template>元素的特殊结构上:<template>的内部内容并不会直接挂载到主DOM树中,而是存储在它的content属性对应的DocumentFragment里。你直接调用template.getElementsByTagName('link')是在<template>元素本身的子节点中查找,但这些子节点实际上并不在常规DOM层级里,自然找不到目标<link>。
修正后的代码
const templates = [...document.getElementsByTagName('template') || []] console.log(`Found ${templates.length} template(s)`) templates.forEach((template) => { // 从template.content中查找link元素 const links = [...template.content.getElementsByTagName('link') || []] console.log(`Found ${links.length} link(s)`) })
额外补充两点优化建议:
- 用
forEach替代map更合适,因为你只是遍历执行打印操作,不需要返回新数组,map更适合数组转换场景。 - 也可以用
querySelectorAll简化写法:template.content.querySelectorAll('link'),效果和getElementsByTagName一致。
内容的提问来源于stack exchange,提问作者ThomasReggi
相关产品推荐
相关产品推荐

