How to add, modify, or delete HTML elements dynamically with JavaScript?

To add, modify, or delete HTML elements dynamically with JavaScript, you can use the Document Object Model (DOM) methods and properties. Here are the steps for each action:

  1. Adding an HTML element dynamically:
  • Create the element using the createElement method.
  • Optionally, set attributes and properties for the element.
  • Append the element to an existing element using the appendChild or insertBefore method.

Example:

// Create a new paragraph element var newParagraph = document.createElement("p"); // Set text content for the paragraph newParagraph.textContent = "This is a dynamically added paragraph."; // Append the paragraph to an existing element document.getElementById("container").appendChild(newParagraph);
  1. Modifying an HTML element dynamically:
  • Get the element you want to modify using getElementById, querySelector, or similar methods.
  • Use the element's properties and methods to modify its content, attributes, or style.

Example:

// Modify an existing paragraph's content var paragraph = document.getElementById("myParagraph"); paragraph.textContent = "This paragraph has been modified.";
  1. Deleting an HTML element dynamically:
  • Get the parent element of the element you want to delete.
  • Use the removeChild method on the parent element to remove the desired child element.

Example:

// Deleting an existing paragraph var container = document.getElementById("container"); var paragraph = document.getElementById("myParagraph"); container.removeChild(paragraph);

These are just basic examples, and there are many more methods and properties available in the DOM API for more advanced use cases.