简体   繁体   English

li元素的childnode给出[#text, <ul> ...... </ul> ,#text]

[英]childnode of li element gives [#text, <ul>​…​</ul>​, #text]

Here I create a chat conversation. 在这里,我创建了一个聊天对话。

The child nodes of the li element with id="topOfStack" ie li元素的子节点,其id="topOfStack"

document.querySelector('#topOfStack').childNodes

results with: 结果:

[#text, <ul>​…​</ul>​, #text]

The HTML code for the my problem is below 我的问题的HTML代码如下

<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>​] . 但是当我动态创建一个新的“ li”元素并添加到chat(ul元素)且id =“ topOfStack从上一个元素中删除并添加到新添加的元素中时,子节点只是[<ul>​…​</ul>​]

Why are #text added by default? 为什么默认情况下添加#text? or what role do they play? 或他们扮演什么角色?

Do you see the spaces from the opening <ul> back to the beginning of the line? 您看到从开头<ul>到行首的空格了吗? 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. 您只需将一个元素节点直接添加到另一个节点即可。

Those text nodes represent text to the left and right of your ul tags. 这些文本节点代表ul标签左侧和右侧的文本。 They're supposed to be there to signify that text. 他们应该在那里表示该文本。 When you dynamically create an <li> tag with just a <ul> tag in it, that text isn't there. 当动态创建仅带有<ul>标记的<li>标记时,该文本将不存在。 You could use .children instead of .childNodes to get just the elements: 您可以使用.children而不是.childNodes来获取元素:

document.querySelector('#topOfStack').children; //HTMLCollection: [<ul>...</ul>]

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

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