Search code examples
javascriptappendchild

Include a name attribute while adding to an <ol>


I'm working on a website that has a dynamic list in it and I want to be able to access individual elements in the list.

Is there a way to add a name to each element when using appendChild()?

This is my function:

function addOrder(theName, thePrice) {
    var li = document.createElement("li");
    var t = document.createTextNode(theName);
    li.appendChild(t);
    document.getElementById("cart").appendChild(li);
}

Solution

  • Do you mean adding a name or data to each element so you can access it at some later time in JS? If so you would want a data-attribute, which you set by using the dataset property.

    function addOrder(theName, thePrice) {
      var li = document.createElement("li");
    
      // Add a data attribute with name of data-name and value of theName:
      li.dataset.name = theName;
    
      var t = document.createTextNode(theName);
      li.appendChild(t);
      document.getElementById("cart").appendChild(li);
    }
    

    In future code you can now look for a list item with a specific name by using something like this: document.querySelectorAll("[data-name='some name']"); or you could get all list items and filter them:

    const listItems = document.querySelectorAll("#cart li");
    const nameIWantToFind = 'some name';
    const foundName = Array.from(listItems).filter(item => item.dataset.name === nameIWantToFind);
    

    Also, as others have said, you don't need to use createTextNode. You can use textContent instead. Others have suggested innerHTML which will work, but isn't needed if you only plan to insert text, and textContent should have slightly better performance. Here is how you would rewrite the function:

    function addOrder(theName, thePrice) {
      // It's neater to put your DOM elements in variables at the top of the function
      var cart = document.getElementById("cart");
    
      var li = document.createElement("li");
    
      // Add the text inside the `li` element:
      li.textContent = theName;
    
      // Add a data attribute with name of data-name and value of theName:
      li.dataset.name = theName;
    
      // Append the `li` element to the `#cart` using the variable we defined at the top of the function:
      cart.appendChild(li);
    }