I'm developing a Google Chrome extension and I want to add <li> to <ul> tag via JavaScript:

var newLI = document.createElement("LI");
var ul = document.getElementById('tag_list');
ul.appendChild(newLI);
newLI.innerHTML = "<a href=\"dddaaaa\">" + json + "</a>";

and HTML:

<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:

Cannot call method 'appendChild' of null

I can't remove the template tag so I have to change JavaScript code. Any idea about why getElementById doesn't work if a tag is in a custom tag <template>?

有帮助吗?

解决方案

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top