2

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?

0

2 Answers 2

5

Those 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>]
4
  • element.children is supported by IE, even old versions.
    – Rob W
    Jul 5, 2014 at 19:52
  • It says it has basic support on Element, but not on Document. Same thing with Safari. Jul 5, 2014 at 19:53
  • That does not matter. .children is only intersting for Element nodes. A document only has one child node, namely the root. document.children is equivalent to [document.documentElement].
    – Rob W
    Jul 5, 2014 at 19:56
  • 1
    Hm...I remember a StackOverflow question where a program didn't work on IE and Safari because of .children, though...Oh, well. I guess I must've misunderstood the accepted answer. Jul 5, 2014 at 20:04
4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.