Try this exercise. Fill in the missing part by typing it in.
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:
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();
Write the missing line below.