Computer >> Computer tutorials >  >> Programming >> Javascript

How would I add a newline in an Unordered List (UL) from JavaScript?


To add a newline in Unordered List, use the document.querySelector().append(). Following is the code −

Example

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
   h1{
      font-size: 2.50rem;
   }
   h2, label{
      font-size: 1.50rem;
   }
</style>
</head>
<body>
<h1>Adding Name Demo</h1>
<div>
<label>Enter The Name:</label>
<input class="txtName" type="text" />
<button class="btnName">Save</button>
</div>
<h2>List Of Name</h2>
<ul class="listOfName"></ul>
<script>
   const buttonName = document.querySelector('.btnName')
   const addName = e => {
      let nameTxt = document.querySelector('.txtName'),
      name = nameTxt.value.trim()
      if (name) {
         let tagLi = document.createElement('li')
         tagLi.textContent = name
         document.querySelector('.listOfName').append(tagLi)
         nameTxt.value = ''
      }
   }
   buttonName.addEventListener('click', addName)
</script>
</body>
</html>

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.

Output

This will produce the following output −

How would I add a newline in an Unordered List (UL) from JavaScript?

Here, I am entering the value in text box, for example the name is ‘John’ −

How would I add a newline in an Unordered List (UL) from JavaScript?

After that, click the Save button. After clicking the Save button, output is as follows −

How would I add a newline in an Unordered List (UL) from JavaScript?

Again, I entered the name ‘Bob’. Now, the updated output is as follows −

How would I add a newline in an Unordered List (UL) from JavaScript?

After clicking the Save button, the output is as follows −

How would I add a newline in an Unordered List (UL) from JavaScript?