繁体   English   中英

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

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

我正在开发一个 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>";

和 HTML:

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

当我删除<template>标签时,此代码运行良好,但使用此标签时出现此错误:

无法调用 null 的方法“appendChild”

我无法删除模板标签,所以我必须更改 JavaScript 代码。 如果标签位于自定义标签<template>为什么getElementById不起作用?

<template标签不是自定义标签; 这是一个新的 HTML5 功能。

<template>标签的全部意义在于它们实际上并不在文档中。
这包括 ID。

您可以使用<template>标记的 DOM 元素的content属性检查或操作模板的content

模板可供您克隆它们。

鉴于此 HTML 代码:

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

如果你尝试这样的事情,它不会工作(将返回null ):

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

方法是:

克隆模板(想想实例化一个类)。

让我在您的基本 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

现在克隆模板:

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

在这里你有一个有效的jsfiddle

暂无
暂无

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

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