Mark As Completed Discussion

Creating and Deleting Elements

In addition to modifying the existing elements in the DOM, you can also create new elements and append them to the DOM or remove existing elements from the DOM.

To create a new element, use the createElement() method on the document object. Specify the element type as the argument, such as 'div', 'p', 'span', etc. This will create a new element of the specified type.

Once you have created the new element, you can set its content using the textContent property. This property allows you to set or retrieve the textual content of an element. For example, you can set the text content of a div element to 'Hello, AlgoDaily!' by assigning the desired text to the textContent property.

You can also add attributes and classes to the new element using appropriate methods like setAttribute() and classList.add(), respectively.

After creating and configuring the new element, you can append it to an existing element by using the appendChild() method. This method takes the new element as an argument and appends it as a child of the specified element.

To remove an element from the DOM, you can use the remove() method directly on the element you wish to remove. This will remove the element from the DOM, including all its children and descendants.

Here's an example that demonstrates creating a new element, setting its content and attributes, appending it to an existing element, and removing an element:

JAVASCRIPT
1// Create a new element
2const newElement = document.createElement('div');
3
4// Set the content and attributes of the new element
5newElement.textContent = 'Hello, AlgoDaily!';
6newElement.classList.add('highlight');
7
8// Append the new element to an existing element
9const container = document.getElementById('container');
10container.appendChild(newElement);
11
12// Remove an element
13const removeElement = document.getElementById('removeMe');
14removeElement.remove();

In this example, a new div element is created and assigned the text 'Hello, AlgoDaily!'. It is then added to the container element by appending it as a child. Finally, the removeMe element is removed from the DOM using the remove() method.

Start practicing creating and deleting elements in the DOM to gain a better understanding of how they work and how you can manipulate the structure of a webpage using JavaScript!

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