Search code examples
javascripthtml-listsappendchild

Could there have been a better way to code this? (Beginner)


Note: i'm trying to learn how to use javascript not jquery or other libraries.

I'm new to javascript and I want to learn how it works and wanted to know if there was a more effective way of coding this.

function myFunction() {
    var domObject = document.createElement("li"),
        userName = document.getElementById("userName").value,
        userNameText = document.createTextNode(userName);

    domObject.appendChild(userNameText);
    document.getElementById("myList").appendChild(domObject);
    document.getElementById("userName").value = "";
}
<body>
    <input type="text" id="userName">
    <button onclick="myFunction()">Click</button>
    <ul id="myList">
        <li>this is</li>
        <li>just a</li>
        <li>test to</li>
        <li>append children</li>
    </ul>
    <script src="main.js"></script>
</body>


Solution

  • domObject is certainly not the best name for a variable (nor is myFunction). Anyway, use addEventListener instead of inline event listeners:

    // you can, of course, use getElementById with an ID attribute
    var input = document.querySelector('input');
    var button = document.querySelector('button');
    var list = document.querySelector('ul');
    
    button.addEventListener('click', function () {
      var li = document.createElement('li');
      li.textContent = input.value;
      input.value = '';
      list.appendChild(li);
    });
    <input type="text">
    <button>Add to list</button>
    <ul></ul>