简体   繁体   中英

Adding TextNode to HTML element with appendChild()

I am trying to create a simple "Shopping List" whereby the user types in the name of the items and then click the "add to List" button to add the items to the list, which it will appear in an ordered list manner. I create an li element for every item added to the list and then add the input value from the user to it through .innerText , then create a textNode out of li which I then append it to sList for it to appear in an ordered list manner.

However, the output I get is [object HTMLLIElement] added to sList instead and it is also not ordered. I think I have misunderstood some concepts about nodes. May I please know what I am doing wrong here?

<html>

<head>
    <title>Complete JavaScript Course</title>
    <style>
    </style>
</head>

<body>
    <div id="message">Complete JavaScript Course</div>
    <div>
        <input type="text" id="addItem">
        <input type="button" id="addNew" value="Add to List">
    </div>
    <div id="output">
        <h1>Shopping List</h1>
        <ol id="sList"> </ol>
    </div>
    <script>
        let button = document.querySelector("#addNew");
        button.addEventListener("click",addOne);
        function addOne(){
            let li = document.createElement("li");
            li.innerText = document.querySelector("#addItem").value;

            let node = document.createTextNode(li);
            document.getElementById("sList").appendChild(node);
        }
        
    </script>
</body>

</html>

You do not need to create text node here

        function addOne(){
            let li = document.createElement("li");
            li.innerText = document.querySelector("#addItem").value;
            document.getElementById("sList").appendChild(li);
        }

 <html> <head> <title>Complete JavaScript Course</title> <style> </style> </head> <body> <div id="message">Complete JavaScript Course</div> <div> <input type="text" id="addItem"> <input type="button" id="addNew" value="Add to List"> </div> <div id="output"> <h1>Shopping List</h1> <ol id="sList"> </ol> </div> <script> let button = document.querySelector("#addNew"); button.addEventListener("click",addOne); function addOne(){ let li = document.createElement("li"); li.innerText = document.querySelector("#addItem").value; document.getElementById("sList").appendChild(li); } </script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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