Mark As Completed Discussion

Modifying HTML Elements

Once you have selected an HTML element using JavaScript, you can modify its attributes, content, and even create entirely new elements.

To create a new element, you can use the createElement method. For example, to create a new div element, you can use the following code:

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

You can then add content to the element using the textContent property. For example, to add the text 'This is a new element!' to the element, you can use the following code:

JAVASCRIPT
1newElement.textContent = 'This is a new element!';

To modify the element's attributes, you can use methods like setAttribute and classList. For example, to set the id attribute to 'myElement' and add a class of 'myClass' to the element, you can use the following code:

JAVASCRIPT
1newElement.setAttribute('id', 'myElement');
2newElement.classList.add('myClass');

Finally, you can append the element to the DOM by selecting a parent element and using the appendChild method. For example, to append the new element to an element with the id 'container', you can use the following code:

JAVASCRIPT
1const container = document.getElementById('container');
2container.appendChild(newElement);

Take a moment to try modifying HTML elements using JavaScript in your own project. You can use the code snippet below as a starting point:

JAVASCRIPT
1// Create a new element
2const newElement = document.createElement('div');
3
4// Add content to the element
5newElement.textContent = 'This is a new element!';
6
7// Modify the element's attributes
8newElement.setAttribute('id', 'myElement');
9newElement.classList.add('myClass');
10
11// Append the element to the DOM
12const container = document.getElementById('container');
13container.appendChild(newElement);
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment