The following example code demonstrates How to Add a Bulleted List to a Paragraph with a Specific ID.

See the previous Example: https://www.programmingempire.com/how-to-add-a-bulleted-list-in-a-paragraph-using-javascript/

The following program also creates a bulleted list in the method addList(). When user clicks on the button, the code adds the list to the paragraph. However, once it is added to the paragraph, it doesn’t add another instance of the list. Because, here, we also add the ID of the list. Before, creating and adding the list, we check whether the list is already there or not. For this purpose, we check whether the list with ID ‘mylist’ is null or not. If it is null, we proceed to create and add the list. Otherwise, we don’t create it.

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript createElement</title>
    <script>
       function addList()
       {
           var para=document.getElementById('p1');
           str1='First Item';
	   str2='Second Item';
           str3='Third Item';

           var mylist=document.getElementById('mylist');
           if(mylist==null){
           	var list1=document.createElement('UL');
          	list1.id='mylist';
           	var item=document.createElement('LI');
           	var text=document.createTextNode(str1);
           	item.appendChild(text);
	   	list1.appendChild(item);

           	var item=document.createElement('LI');
           	var text=document.createTextNode(str2);
           	item.appendChild(text);
	   	list1.appendChild(item);

           	var item=document.createElement('LI');
           	var text=document.createTextNode(str3);
           	item.appendChild(text);
	   	list1.appendChild(item);

	   	para.appendChild(list1);
	   }
	   para.innerHTML+="Bulleted List with ID: mylist";
	   
       }
    </script>
<body>
	<p id='p1'></p>
	<button onclick="addList()">Add Bulleted List</button>
</body>
</html>

Output

A Program Demonstrating How to Add a Bulleted List to a Paragraph with a Specific ID
A Program Demonstrating How to Add a Bulleted List to a Paragraph with a Specific ID

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Creating Classes in JavaScript

programmingempire

Princites

IITM Software Development Cell