How to Manipulate HTML Elements with JavaScript?

Estimated read time 2 min read

JavaScript provides several methods to manipulate HTML elements, such as adding or removing elements, changing the content of an element, and changing the styles of an element. Here are some of the most common methods for manipulating HTML elements with JavaScript:

  1. Selecting elements: You can use the document.getElementById() method to select an element by its ID, or the document.querySelector() method to select an element using CSS-style selectors. For example:
// Select an element by ID
let header = document.getElementById("header");

// Select an element using a CSS selector
let listItems = document.querySelectorAll("li");
  1. Changing the content of an element: You can use the innerHTML property to change the content of an element. For example:
header.innerHTML = "New Header Text";
  1. Changing the styles of an element: You can use the style property to change the styles of an element. For example:
header.style.color = "red";
header.style.backgroundColor = "yellow";
  1. Adding elements: You can use the document.createElement() method to create a new element, and then append it to an existing element using the appendChild() method. For example:
// Create a new element
let newListItem = document.createElement("li");
newListItem.innerHTML = "New List Item";

// Append the new element to the list
let list = document.querySelector("ul");
list.appendChild(newListItem);
  1. Removing elements: You can use the removeChild() method to remove an element. For example:
list.removeChild(newListItem);

These are just a few examples of the methods available for manipulating HTML elements with JavaScript. For more information, you can refer to the official JavaScript documentation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply