Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 2 - HTML DOM

2.3 Creating And Removing DOM Elements

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:

  1. Create the element.
  2. Set its properties or attributes.
  3. Append it to the document.

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:

  1. Select the element you want to remove.
  2. Use the 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.