D
D
Dmitry2018-02-14 11:31:37
JavaScript
Dmitry, 2018-02-14 11:31:37

How to create a list and insert list items into it?

Hello, how to create a list in javascript, insert list items with info into it and add this list to the container. The difficulty is that the container is initially empty and the appendChild method is not suitable. The lists will be added one by one to the initially empty container.
Tried like this:

var viewport  = document.getElementById('viewport');
        var fragment = document.createDocumentFragment();
        var inputs = document.getElementsByName('data');

        for ( var i = 0; i < inputs.length; i++ ) {
            var li = document.createElement('li');
            li.textContent = inputs[i].value;
            fragment.appendChild(li);
        }

        viewport.appendChild(fragment);

It works like that, but throws dashes right into the viewport, but how to insert them into the ul first?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-02-14
@ddimonn8080

let ul =  document.createElement('ul');
for (...) {
  var li = document.createElement('li');
  ul.appendChild(li)
}
viewport.appendChild(ul);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question