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:
createElement
method.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);
getElementById
, querySelector
, or similar methods.Example:
// Modify an existing paragraph's content
var paragraph = document.getElementById("myParagraph");
paragraph.textContent = "This paragraph has been modified.";
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.