skip to Main Content

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)
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)`)
})
Example HTML:
<template></template>
<template>
  <link/>
</template>
<template></template>

2

Answers


  1. Chosen as BEST ANSWER

    I was missing content

    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)`)
    })
    Example HTML:
    <template></template>
    <template>
      <link/>
    </template>
    <template></template>


  2. You need to use

    template.content
    

    property to correctly access to template html content.

    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)`)
    })
    <template></template>
    <template>
      <link/>
    </template>
    <template></template>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search