0

I'm making a JS application that automatically another textbox on user input. I'm not however sure how I append an input to a li

The end result I want to get at is this:

<ul id="lst">
  <li>Item1: <input type="text"></li>
  <li>Item2: <input type="text"></li>
  <!-- more li added on button press -->
</ul>

what I got so far is this:

var onClick = function() {
  var ul = document.getElementById('lst'),
      li = document.createElement('li');
  li.appendChild(document.createTextNode('Item' + counter + ': '));
  counter++;
  ul.appendChild(li);
}

How do I also append the <input type="text"> node?

1
  • I think this is what you are looking for: stackoverflow.com/a/5656401/4298881. Construct a input node and append it after you append the Item Commented Aug 19, 2015 at 17:23

2 Answers 2

1

The same way you added the text to the element.

var onClick = function() {
  var ul = document.getElementById('lst'),
      li = document.createElement('li'),
      input = document.createElement('input');
  input.type="text";
  li.appendChild(document.createTextNode('Item' + counter + ': '));
  li.appendChild(input);
  counter++;
  ul.appendChild(li);
}
Sign up to request clarification or add additional context in comments.

Comments

0

It's probably easier to use a label element as well, and append that along with an input

var onClick = function() {
    var ul    = document.getElementById('lst'),
        li    = document.createElement('li'),
        label = document.createElement('label'),
        input = document.createElement('input');

    label.text = "Item " + counter + ":";
    li.appendChild(label);
    //input.type = "text";
    li.appendChild(input); //defaults to type text
    ul.appendChild(li);

    counter++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.