问题描述
在这里我创建了一个聊天对话。
id =topOfStack
document.querySelector('#topOfStack')。childNodes
结果为:
[#text,< ul> ...< / ul> ,#text]
我的问题的HTML代码如下
< div id =container>
< ul id =chat>
< li class =right>
< ul>
< li>< span> Hello< / span>< / li>
< li>< span>你在做什么?< / span>< / li>
< / ul>
< / li>
< li class =leftid =topOfStack>
< ul>
< li>< span>观看电影< / span>< / li>
< li>< span> u?< / span>< / li>
< / ul>
< / li>
< / ul>
< / div>
但是当我动态地创建一个新的li元素并追加到chat(ul元素) id =topOfStack从前一个中移除并添加到新添加的元素中,则子节点仅为 [< ul> ...< / ul>]
。
为什么默认添加#text?或者它们扮演什么角色?
您是否看到< ul>
开头的空格返回到行首?这就是全部文本。解析器无法知道那些空格(对你而言)并不重要,因此为它们创建了一个文本节点。
< li class =leftid = topOfStack> |< line break here
< ul>
^^^^
此处
当你动态地创建元素时,没有什么可以解析的,你只需要直接添加一个元素节点到另一个元素中即可。
Here I create a chat conversation.
The child nodes of the li element with id="topOfStack"
i.e.
document.querySelector('#topOfStack').childNodes
results with:
[#text, <ul>…</ul>, #text]
The HTML code for the my problem is below
<div id="container">
<ul id="chat">
<li class="right">
<ul>
<li><span>Hello</span></li>
<li><span> What are you doing?</span></li>
</ul>
</li>
<li class="left" id="topOfStack">
<ul>
<li><span>Watching Movie</span></li>
<li><span>u?</span></li>
</ul>
</li>
</ul>
</div>
But when I dynamically create a new "li" element and append to the chat(ul element) with id="topOfStack removed from the previous one and added to the newly appended element, the child nodes are only [<ul>…</ul>]
.
Why are #text added by default? or what role do they play?
Do you see the spaces from the opening <ul>
back to the beginning of the line? That's all text. The parser cannot know that those whitespaces are not significant (to you) and therefore creates a text node for them.
<li class="left" id="topOfStack"> |< line break here
<ul>
^^^^
spaces here
When you dynamically create the elements, there is nothing to parse. You just directly add an element node to another one.
这篇关于li元素的childnode给出[#text,< ul> ...< / ul>,#text]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!