JavaScript Create Element List

The document.createElement() method in JavaScript is used to create a new HTML element with a specified tag name. The method takes a single argument, which is the tag name of the element to be created. For example, document.createElement(“div”) creates a new div element. The newly created element can be accessed and modified through the DOM API, such as adding content, attributes, and styles to the element. It can also be added to the document by using methods such as appendChild() or insertAdjacentHTML().

In the below example we will be creating a dynamic list, all the elements are created using JavaScript, adding the button for interaction when the user wants to add new people to the list.

const myArr = [‘Laurence’,’Susan’,’Lisa’];

const output = document.querySelector(‘.output’);

const btn = document.createElement(‘button’);

btn.textContent = ‘Add Person’;

output.append(btn);

const myInput = document.createElement(‘input’);

myInput.setAttribute(‘type’,’text’);

myInput.value = ‘Lawrence’;

output.prepend(myInput);

const ul = document.createElement(‘ul’);

output.append(ul);

build();

btn.addEventListener(‘click’,addPerson);

function addPerson(){

   const newPerson = myInput.value;

   myArr.push(newPerson);

   adder(newPerson);

   console.log(myArr);

}

function adder(person){

   const li = document.createElement(‘li’);

   li.textContent = person;

   ul.append(li);

}

function build(){

   myArr.forEach(ele => {

       adder(ele);

   })

}