JavaScript DOM Manipulation: document.createElement() and Element.remove()

1. document.createElement()

Definition

document.createElement() is a JavaScript method that creates a new HTML element node with the specified tag name. The created element exists in memory and must be appended to the DOM to be visible.

Important Points

Syntax

const element = document.createElement(tagName);

tagName: A string specifying the element type (e.g., 'div', 'img', 'p').
Returns: A new HTML element node.

Example

Create a div, add a class, set text content, and append it to the body:

const div = document.createElement('div');
div.classList.add('my-class');
div.innerText = 'Hello, World!';
document.body.append(div);

Practical Example

This example generates Pokémon images with their index numbers based on user input.

2. Element.remove()

Definition

Element.remove() is a JavaScript method that removes an element (and its children) from the DOM. It is called directly on the element, requiring no reference to its parent.

Important Points

Syntax

element.remove();

element: The DOM element to remove.
No parameters or return value.

Example

Remove a specific div element:

const div = document.querySelector('.my-div');
div.remove();