Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 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?

like image 862
Saiteja Parsi Avatar asked Jan 27 '26 17:01

Saiteja Parsi


1 Answers

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>]
like image 172
Noble Mushtak Avatar answered Jan 30 '26 07:01

Noble Mushtak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!