Search code examples
javascripthtmlhtml-listsinnerhtmlappendchild

Adding html code instead of plain text to ul with appendchild or other method?


document.getElementById('addplace').addEventListener('click', function() {
    addplace();
  });

function addplace () {
  var node = document.createElement("li");                 // Create a <li> node
  var textnode = document.createTextNode("<b>Waypoint</b>");         // Create a text node
  node.appendChild(textnode);                              // Append the text to <li>
  document.getElementById("waypoints").appendChild(node);
}  
<input type="submit" id="addplace" value="Add One!">  
<ul id="waypoints">
</ul>

I need this to make the html code work in each new li. I tried innerHTML as well and was only able to add plain text. How to make "Waypoint" bold instead of it showing the text "Waypoint" enclosed by b tags?

It's specifically for adding a new Google Places autocomplete field and an image of an "x" to delete the li so i'm looking for a solution that can pass values / be JavaScript friendly for the rest of my application mentioned in this question.

Thanks


Solution

  • Instead of creating a text node, create a node for <b> tag and set its text content.

    function addplace () {
      var node = document.createElement("li");                 // Create a <li> node
      var textNode = document.createElement("b"); //create a <b> tag
      textNode.textContent = "Waypoint"; //set <b> tag's text
      node.appendChild(textnode);  //Append the <b> tag                            
      document.getElementById("waypoints").appendChild(node);
    }  
    

    DEMO

    If you want to set different html elmenets inside of li more than a <b> element, then you could use the below,

    function addplace() {
      var node = document.createElement("li"); // Create a <li> node
      node.innerHTML = "<b>waypoints</b>"               
      document.getElementById("waypoints").appendChild(node);
    }
    

    DEMO