JAVASCRIPT Tutorial

Modifying HTML Content

Key Concepts

  • innerHTML: Sets or returns the HTML content of an element, including all its children.
  • textContent: Sets or returns the text content of an element, excluding any HTML tags.
  • innerText: Sets or returns the text content of an element, including any white space.
  • createElement: Creates a new HTML element.
  • appendChild: Adds a new child element to the end of an element's child list.
  • removeChild: Removes a child element from an element's child list.
  • insertBefore: Inserts a new child element before a specified child element in an element's child list.

Practical Steps

  1. Select the element: Use a query selector such as document.querySelector() or document.querySelectorAll() to select the element you want to modify.
  2. Set or retrieve content: Use the appropriate property (e.g., innerHTML, textContent, innerText) to set or retrieve the element's content.
  3. Create new elements: Use createElement() to create new HTML elements and customize their attributes and content.
  4. Add or remove elements: Use appendChild(), removeChild(), or insertBefore() to manipulate the element's child list.

Example

// Change the text content of a heading
const heading = document.querySelector('h1');
heading.textContent = 'New Heading Text';

// Add a new paragraph element
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);

// Remove an existing element
const oldElement = document.querySelector('#oldElement');
document.body.removeChild(oldElement);