You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:27:04