Search code examples
javascripthtmldomhtml5-template

`getElementById` doesn’t find elements inside `<template>` tag


I want to add <li> to <ul> tag via JavaScript:

const newLI = document.createElement("LI");
const ul = document.getElementById("tag_list");

ul.appendChild(newLI);
newLI.innerHTML = "<a href=\"dddaaaa\">" + json + "</a>";
<template id="box#add-feeds">
  <ul class="search-ac" id="tag_list" name="tag_list"></ul>
</template>

When I remove the <template> tag, this code works well, but with this tag I have this error:

TypeError: Cannot call method 'appendChild' of null

I can’t remove the <template> tag so I have to change the JavaScript code. Any idea about why getElementById doesn’t find an element if it’s in a <template> tag?


Solution

  • The <template tag is not a custom tag; it's a new HTML5 feature.

    The whole point of <template> tags is that they aren't actually in the document.
    That includes IDs.

    You can examine or manipulate the contents of the template using the content property of the <template> tag's DOM element.