This HTML file includes the JavaScript code that demonstrates how to access and manipulate DOM elements with class names and ids. The code modifies the innerHTML of the elements with the class "example" and adds/removes/toggles classes on the element with the id "myId".
It should be noted that if you use className property to change classes it will replace all the existing classes with the new classes, while if you use classList.add() or classList.remove() it will only add or remove the class you specify.
Accessing and modifying the DOM:
<h1 div id="myId"> Hello Class </h1>
// Access an element by its ID
let element = document.getElementById("myId");
// Modify the innerHTML of an element
element.innerHTML = "New Content";
<h1 div id="myId"> Hello Class </h1>
// Access an element by its class name
let elements = document.getElementsByClassName("myClass");
// Access an element by its tag name
let elements = document.getElementsByTagName("p");
Traversing the DOM:
Copy code
// Access the parent node of an element
let parent = element.parentNode;
// Access the children of an element
let children = element.children;
// Access the first child of an element
let firstChild = element.firstChild;
// Access the last child of an element
let lastChild = element.lastChild;
Creating and inserting new elements:
Copy code
// Create a new element
let newElement = document.createElement("div");
// Set the innerHTML of the new element
newElement.innerHTML = "New Content";
// Append the new element to an existing element
element.appendChild(newElement);
// Insert the new element before an existing child element