dynamically create html element in javascript

htmljavascript

To dynamically create an HTML element in JavaScript, you can use the document.createElement() method. This method takes a string argument that specifies the type of element to create, and returns a new element object.

Here is an example of how you can use document.createElement() to create a new div element:

let div = document.createElement('div');

You can then set the attributes and content of the element by using its properties and methods. For example, you can set the innerHTML property to add content to the element, or use the setAttribute() method to set an attribute.

Here is an example of how you can create a new div element and add content and an attribute to it:

let div = document.createElement('div');
div.innerHTML = 'Hello World';
div.setAttribute('class', 'my-class');

To add the element to the DOM, you can use the appendChild() method of the parent element.

Here is an example of how you can append the div element to the body of the page:

document.body.appendChild(div);

This will add the div element to the end of the body element, with the content “Hello World” and the class “my-class”.

For more information on creating and manipulating HTML elements in JavaScript, you can refer to the JavaScript documentation: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement.