Search code examples
javascriptparent-childchildren

Add id to children and store them as array to list


I have different buttons without id like this:

<div id="buttons">
  <button data-note="n1">One</button>
  <button data-note="n2">Two</button>
</div>

I cannot access them by .button since I have many, like 20 or so. Can I access them by their data-note attribute? querySelector selects the first one, second or all of them. Can I specifically select them, maybe put them an id?

What I actually want is to store the data-note as an Array, so have to convert that data into arrays as list to add to the HTML.

I supposed it is also possible without the id?
I might have to create for each button a function that by clicking them it stores that information as array into a list that I can access later if called, but I don't know how to select these children. If possible not by nodelist numbers, but by data, or if by nodelist then.

It might be a problem depending on the browser as they count 0,1,2 or 1,3,5... Is it possible to use getElementById and select a specific number of child?

To addEventListener I need to select each one of the buttons.


Solution

  • If you just want the notes data in a unordered list, then you can do the following:

    // Get all the buttons
    let buttons = document.getElementsByTagName("button");
    
    // Get the "clear" button as it has a special function
    let clear = buttons[buttons.length - 1];
    
    // Create an unordered list
    let ul = document.createElement("ul");
    
    // Iterate through the buttons
    for (let button of buttons) {
    
      // Add the event listener to each button
      button.addEventListener("click", (e) => {
    
        // Clear the unordered list if the clear button was pressed
        if (e.target === clear) {
          ul.innerHTML = "";
          return;
        }
    
        // For each button create a list item
        let li = document.createElement("li");
    
        // Set it's innerText attribute to be the data-note
        li.innerText = `${button.dataset.note} - ${e.target.style.backgroundColor}`;
    
        // Append it to the unordered list
        ul.append(li);
      });
    }
    
    // Append the list to the body
    document.body.append(ul);
    button {
      border: none;
      color: white;
      padding: 10px 20px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 14px;
      margin: 4px 2px;
      cursor: pointer;
    }
    <h2>Buttons Game</h2>
    <p>Click the buttons to add them to the list, press clear to reset</p>
    <button data-note="n1" style="background-color: red;">red</button>
    <button data-note="n2" style="background-color: green;">green</button>
    <button data-note="n3" style="background-color: orange;">orange</button>
    <button data-note="n4" style="background-color: blue;">blue</button>
    <button id="clear" style="color: black; border: 1px solid black;">clear</button>