英文:
How do I query within `<template>` element?
问题
这里有什么问题?为什么我不能选择模板中的link
?
找到了3个模板
找到了0个链接
找到了0个链接
找到了0个链接
示例HTML:
<template></template>
<template>
<link/>
</template>
<template></template>
英文:
What am I doing wrong here? Why am I not able to select the link
within the template?
Found 3 template(s)
Found 0 link(s)
Found 0 link(s)
Found 0 link(s)
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const templates = [...document.getElementsByTagName('template') || []]
console.log(`Found ${templates.length} template(s)`)
templates.map((template) => {
const links = [...template.getElementsByTagName('link') || []]
console.log(`Found ${links.length} link(s)`)
})
<!-- language: lang-html -->
Example HTML:
<template></template>
<template>
<link/>
</template>
<template></template>
<!-- end snippet -->
答案1
得分: 2
我遗漏了content
const templates = [...document.querySelectorAll('template') || []]
console.log(`找到 ${templates.length} 个模板(s)`)
templates.map((template) => {
const links = [...template.content.querySelectorAll('link') || []]
console.log(`找到 ${links.length} 个链接(s)`)
})
示例HTML:
<template></template>
<template>
<link/>
</template>
<template></template>
英文:
I was missing content
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const templates = [...document.querySelectorAll('template') || []]
console.log(`Found ${templates.length} template(s)`)
templates.map((template) => {
const links = [...template.content.querySelectorAll('link') || []]
console.log(`Found ${links.length} link(s)`)
})
<!-- language: lang-html -->
Example HTML:
<template></template>
<template>
<link/>
</template>
<template></template>
<!-- end snippet -->
答案2
得分: 0
你需要使用以下代码来正确访问模板的HTML内容:
template.content
以下是您提供的代码的翻译:
const templates = [...document.getElementsByTagName('template') || []];
console.log(`找到 ${templates.length} 个模板`);
templates.map((template) => {
const links = template.content.querySelectorAll('link');
const linksArray = links ? Array.from(links) : [];
console.log(`找到 ${linksArray.length} 个链接`);
})
<template></template>
<template>
<link></link>
</template>
<template></template>
英文:
You need to use
template.content
property to correctly access to template html content.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const templates = [...document.getElementsByTagName('template') || []]
console.log(`Found ${templates.length} template(s)`)
templates.map((template) => {;
const links = template.content.querySelectorAll('link');
const linksArray = links ? Array.from(links) : [];
console.log(`Found ${linksArray.length} link(s)`)
})
<!-- language: lang-html -->
<template></template>
<template>
<link/>
</template>
<template></template>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论