Adding new element and set id in javascript

In JavaScript, you can add a new element to the DOM and set its ID using the following methods:

Method 1: Using the createElement method

const newElement = document.createElement('div'); // create a new div element
newElement.id = 'myNewElement'; // set the ID of the element
document.body.appendChild(newElement); // add the element to the page

Method 2: Using the innerHTML property

const newElement = document.createElement('div'); // create a new div element
newElement.innerHTML = 'Hello World!'; // set the content of the element
newElement.id = 'myNewElement'; // set the ID of the element
document.body.appendChild(newElement); // add the element to the page

Method 3: Using the document.getElementById method

const newElement = document.createElement('div'); // create a new div element
newElement.id = 'myNewElement'; // set the ID of the element
document.body.appendChild(newElement); // add the element to the page

In all cases, you need to create a new element using document.createElement, set its ID using the id property, and then add it to the page using appendChild.

Note that if you want to add the element to a specific parent element, you can use the appendChild method on that element instead of document.body. For example:

const parentElement = document.getElementById('myParent');
const newElement = document.createElement('div');
newElement.id = 'myNewElement';
parentElement.appendChild(newElement);

This will add the new element to the element with the ID myParent.