Learn Dynamic HTML With JS
Lesson 1 - HTML JS Relationship
Lesson 3 - Browser BOM
Lesson 4 - Basic Interaction
Lesson 5 - Manipulating CSS
Lesson 6 - HTTP Requests
Lesson 7 - Form Handling
In this lesson, we'll explore how to manipulate HTML elements.
Creating DOM Elements
Creating a new DOM element is straightforward and involves a few basic steps:
Let's look at the following example:
<!DOCTYPE html> <html> <head> <title>Adding Elements</title> </head> <body> </body> <script> let textDiv = document.createElement('div'); textDiv.id = 'add_text'; textDiv.className = 'add_text_class'; textDiv.innerHTML = 'This is some text!!!'; document.body.appendChild(textDiv); </script> </html>
In the example above, we first created a div
element, assigned it an id
and a class
, set its content using innerHTML
, and finally appended it to the body
of our HTML document using appendChild()
.
Removing DOM Elements
Removing a DOM element is also straightforward. Here are the basic steps:
remove()
method or remove it from its parent.Consider the example below:
<!DOCTYPE html> <html> <head> <title>Removing Elements</title> </head> <body> <button id="myButton">Click me to remove</button> </body> <script> let newButton = document.getElementById('myButton'); newButton.addEventListener('click', function() { newButton.remove(); }); </script> </html>
In this example, we selected the button with the id myButton
and added an event listener to remove it when clicked, using the remove()
method.