Search code examples
javascripthtmlinputinnerhtmlappendchild

innerHTML (or other method): append li to ul, with <input/> including attributes


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

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

The above snippet successfully adds an input field to the ul when the button is clicked. However when I add attributes to the input field the submit button no longer works.

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

    function addplace() {
      var node = document.createElement("li"); // Create a <li> node
      node.innerHTML = "<input class="field" placeholder="Where to begin?" onFocus="geolocate()" type="text" />"               
      document.getElementById("waypoints").appendChild(node);
    }
    <ul id="waypoints"></ul>
    <input type="submit" id="addplace" />        

Thanks.


Solution

  • You have to either escape("\"") the double quotes inside the string or use single quotes("'") in the place of double quotes to fix your issue.

    function addplace() {
      var node = document.createElement("li"); // Create a <li> node
      node.innerHTML = "<input class='field' placeholder='Where to begin?' onFocus='geolocate()' type='text' />"               
      document.getElementById("waypoints").appendChild(node);
    }
    

    The solution by escaping the double quotes,

    node.innerHTML = "<input class=\"field\" placeholder=\"Where to begin?\" onFocus=\"geolocate()\" type=\"text\" />"