To add and delete HTML elements in JavaScript, you can use the DOM (Document Object Model) manipulation methods. Here's how you can achieve it:
Adding HTML Elements: To add HTML elements dynamically using JavaScript, you can follow these steps:
1. Access the parent element to which you want to append the new element. This can be done using various methods like getElementById, getElementsByClassName, getElementsByTagName, etc.
2. Create the new HTML element using the createElement method. Specify the element type by passing the appropriate tag name as an argument.
3. Set any desired attributes or properties for the new element using methods like setAttribute or by directly assigning values to properties.
4. Optionally, add content to the new element using textContent or innerHTML.
5. the new element to the parent element using the appendChild method.
Here's an example that adds a new paragraph element to an existing div with the ID "myDiv":
var parentElement = document.getElementById("myDiv");
var newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
parentElement.appendChild(newParagraph);
Deleting HTML Elements: To delete HTML elements using JavaScript, you can follow these steps:
1. Access the element you want to delete. This can be done using the same methods mentioned above.
2. Use the remove method on the selected element to delete it.
Here's an example that deletes an existing paragraph element:
var paragraphElement = document.getElementById("myParagraph");
paragraphElement.remove();
By incorporating JavaScript into a Java Training course in Indore, students can gain a broader understanding of web development and acquire skills that are highly relevant in the industry, especially when building interactive and dynamic web applications.