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?
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?
Share Improve this question edited Jul 6, 2014 at 1:48 Lee Taylor 7,99416 gold badges37 silver badges53 bronze badges asked Jul 5, 2014 at 19:34 Saiteja ParsiSaiteja Parsi 4541 gold badge6 silver badges16 bronze badges 02 Answers
Reset to default 5Those text nodes represent text to the left and right of your ul
tags. 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. You could use .children
instead of .childNodes
to get just the elements:
document.querySelector('#topOfStack').children; //HTMLCollection: [<ul>...</ul>]
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.