简体   繁体   English

document.getElementById 不适用于<template>自定义标签

[英]document.getElementById doesn't work with <template> custom tag

I'm developing a Google Chrome extension and I want to add <li> to <ul> tag via JavaScript:我正在开发一个 Google Chrome 扩展程序,我想通过 JavaScript 将<li>添加到<ul>标签:

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

and HTML:和 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:当我删除<template>标签时,此代码运行良好,但使用此标签时出现此错误:

Cannot call method 'appendChild' of null无法调用 null 的方法“appendChild”

I can't remove the template tag so I have to change JavaScript code.我无法删除模板标签,所以我必须更改 JavaScript 代码。 Any idea about why getElementById doesn't work if a tag is in a custom tag <template> ?如果标签位于自定义标签<template>为什么getElementById不起作用?

The <template tag is not a custom tag; <template标签不是自定义标签; it's a new HTML5 feature.这是一个新的 HTML5 功能。

The whole point of <template> tags is that they aren't actually in the document. <template>标签的全部意义在于它们实际上并不在文档中。
That includes IDs.这包括 ID。

You can examine or manipulate the contents of the template using the content property of the <template> tag's DOM element.您可以使用<template>标记的 DOM 元素的content属性检查或操作模板的content

Templates are there for you to CLONE them.模板可供您克隆它们。

Given this HTML code:鉴于此 HTML 代码:

<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 ):如果你尝试这样的事情,它不会工作(将返回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:让我在您的基本 html 中添加一个div

<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在这里你有一个有效的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM