Search code examples
javascriptbuttoncreateelement

How to create buttons after each line of the list?


I'd like to display a list of skills and values of a player, and create an increment and decrement button after each line to increase or decrease the value. I've tried to gather lines from other questions related to this problem, but I'm a beginner and can't solve it. Here it is my code:

var text = "<ul>";
var i = 0;

for (i; i < this.skillPoints.length; i++) {
  text +=
    "<li>" +
    this.skillPoints[i]._name +
    " value is: " +
    this.skillPoints[i]._value +
    "</li></br>";

    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(text));

    var btn = document.createElement("BUTTON");
    btn.innerHTML = "Increment";
    entry.appendChild(btn);
}

text += "</ul>";
document.getElementById("list").innerHTML = text;

Solution

  • You are mixing up alot of functios which would work individually. Either decide on adding the text as innerHTML or adding the elementy by appendChild(document.createElement(x)). Also createTextNode() creates HTML encoded output and not what you seek. Last, you should wait to add all to the DOM until the output is completed.

    This is a corrected example as close to your code as possible.

    //REM: For testing
    var skillPoints = [
    	{_name: 'Skill 1', _value: 'a'},
    	{_name: 'Skill 2', _value: 'b'}
    ];
    
    //REM: Start of the list
    var text = "<ul>";
    
    //REM: Removed "this" for testing purposes
    for(var i=0; i < skillPoints.length; i++){
      text += "<li>";
      text += skillPoints[i]._name;
      text += " value is: ";
      text += skillPoints[i]._value;
      text += "</li></br>";
      text += "<button> Increment </button>";
    
      //REM: Not required.. the li gets added as string already in this case. Use either or but not both.
      //var entry = document.createElement('li');
    
      //REM: First, textnode adds encoded HTML and second, the list is not complete yet
      //REM: https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode
      //entry.appendChild(document.createTextNode(text));
    };
    
    text += "</ul>";
    
    //REM: Now that the ul is complete, we add it to the DOM
    //REM: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
    document.body.insertAdjacentHTML('beforeend', text);