Mark As Completed Discussion

In frontend development, there are often cases where you need to create new elements dynamically and append them to the DOM. This can be useful when you want to add new content reactively or generate elements based on user interactions.

To create a new element in JavaScript, you can use the document.createElement() method. This method takes the name of the element you want to create as a parameter. For example, let's say we want to create a div element:

JAVASCRIPT
1const element = document.createElement('div');

Next, you can set the properties and attributes of the element using the corresponding methods. For example, to set the text content of the element, you can use the textContent property:

JAVASCRIPT
1const element = document.createElement('div');
2element.textContent = 'Hello, AlgoDaily!';

Once you have created and configured the element, you can append it to the DOM using the appendChild() method. This method takes the new element as a parameter and adds it as the last child of the specified parent element. For example, to append the new div element to the body element:

JAVASCRIPT
1const element = document.createElement('div');
2element.textContent = 'Hello, AlgoDaily!';
3document.body.appendChild(element);

Now, when the code is executed, a new div element with the text content 'Hello, AlgoDaily!' will be created and appended to the body of the webpage.

By dynamically creating and appending elements, you can easily manipulate the DOM and create interactive and dynamic web pages tailored to your specific needs.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment