[英]Why does removeChild function behave differently with list items and i tag?
I have noticed that removeChild does NOT behave as it does with other elements such as list item. 我注意到removeChild的行为不像其他元素(如列表项)那样。 I am using the i tag for some icons from frontAwesome and want these items removed individually when a button is clicked.
我正在使用i标记来获取来自frontAwesome的某些图标,并希望在单击按钮时分别删除这些项目。
Unfortunately, I can only remove each i tag element only if I use removeChild() function twice. 不幸的是,仅当我两次使用removeChild()函数时,才能删除每个i标记元素。 (Weird!)
(奇怪的!)
What's going on? 这是怎么回事?
HTML: HTML:
<div id="myFonts">
<i>1</i>
<i>2</i>
<i>3</i>
<i>4</i>
<i>5</i>
</div>
Javascript: 使用Javascript:
function FunctionTwo() {
var font = document.getElementById("myFonts");
font.removeChild(font.childNodes[0]);
}
https://codepen.io/anon/pen/EeaYvL https://codepen.io/anon/pen/EeaYvL
EDIT Note: It makes a difference if you use LineBreaks or not! 编辑注意:是否使用LineBreaks会有所不同!
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Here, there are 6 child nodes. 在这里,有6个子节点。 Apparently, the LineBreaks are also considered as child nodes!
显然,LineBreaks也被视为子节点!
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
Here, there are 3 child nodes. 在这里,有3个子节点。 WEIRD - is this a bug?
很奇怪-这是一个错误吗?
childNodes includes all child nodes, including non-element nodes like text and comment nodes.
childNodes包括所有子节点,包括非元素节点,例如文本和注释节点。 To get a collection of only elements, use ParentNode.children instead.
要获取仅元素的集合,请改用ParentNode.children。
Hence, in both the cases, the elements are being removed weirdly. 因此,在两种情况下,这些元素都被怪异地去除了。 You should update
你应该更新
from 从
font.removeChild(font.childNodes[0]);
to 至
font.removeChild(font.children[0]);
For tweaking, https://codepen.io/anon/pen/aazoLK 要进行调整, 请https://codepen.io/anon/pen/aazoLK
Also.. if you notice both of your code closely on your link... 另外..如果您在链接上密切注意两个代码...
Code for <ul id="myList">
<ul id="myList">
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
We see no spaces between tags. 标签之间没有空格。
Whereas, Code for <div id="myFonts">
而
<div id="myFonts">
<div id="myFonts"> <i>1</i> <i>2</i> <i>3</i> <i>4</i> <i>5</i> </div>
You see the empty spaces before the <i>
? 您看到
<i>
前面的空白吗? Those got added as a text node in the childNodes object of your div
那些作为文本节点添加到
div
的childNodes对象中
<div id="myFonts"> <i>1</i> </div>
You could have used exactly the same code that you have currently, if you had chosen to rather Not add spaces before the <i>
tags. 如果您选择在
<i>
标记之前不添加空格,则可以使用与当前完全相同的代码。
For Eg. 例如 like this:
像这样:
<div id="myFonts"><i>1</i><i>2</i><i>3</i><i>4</i><i>5</i></div>
Check modified HTML for div
here: CodePen 在此处检查
div
修改后的HTML: CodePen
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.