user2169502
user2169502

Reputation: 23

`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?

Upvotes: 2

Views: 4006

Answers (2)

sscalvo
sscalvo

Reputation: 485

Templates are there for you to CLONE them.

Given this HTML code:

<template id="add-feeds">
    <ul class="search-ac" id="tag_list" name="tag_list"></ul>
</template>

if you try something like this, it will NOT work (will return null):

var ul = document.getElementById('tag_list'); // ul is *null*

THE WAY TO GO IS:

clone the template (think about it of instantiating a class).

Let me add a div to your base html:

<template id="add-feeds">
    <ul class="search-ac" id="tag_list" name="tag_list"></ul>
</template>

<div id="show_list"></div>   //div used as DOM-entry-point for our new created list

Now clone the template:

var template= document.querySelector("#add-feeds");
my_template_clone = template.content.cloneNode(true); // clone the template 
var my_ul = my_template_clone.getElementById('tag_list'); //now you can find the *ul*

var newLI = document.createElement("LI"); //create random stuff
newLI.innerHTML="hello";
my_ul.appendChild(newLI);  //append it to the ul

var div = document.getElementById('show_list'); 
div.appendChild(my_ul); //now add it into the DOM

Here you have a working jsfiddle

Upvotes: 2

SLaks
SLaks

Reputation: 887807

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.

Upvotes: 2

Related Questions