JavaScript can access and modify all parts of an HTML document via the HTML The Document Object Model (DOM) in HTML .The browser produces a Document Object Model of a web page when it is loaded. The HTML DOM model is built as a hierarchy of Objects:
Document
Your web page is represented by the document object. When you wish to get to any element on an HTML page, you must first get to the document object.
You'll frequently wish to manipulate HTML elements with JavaScript.To do so, you must first locate the components. There are various options for accomplishing this:
JavaScript may change the style of HTML elements thanks to the HTML DOM. Use the above syntax to modify the style of an HTML element. It's important to note that the background color in CSS is written as backgroundColor rather than background-color. This also applies to other styles with several words.
A function named changename is applied to an HTML element with the id="btn" in the example above. When the button is pressed, the function is called.
<body onload="sayhello()">
When a user enters or exits a page, the onload and onunload events are fired. The onload event can be used to determine the visitor's browser type and version, and then load the appropriate version of the web page based on the data.
A mouse-click is represented by the onmousedown, onmouseup, and onclick events. The onmousedown event is started when a mouse button is clicked, followed by the onmouseup event when the mouse button is released, and finally the onclick event when the mouse-click is completed.
The addEventListener() method adds an event handler to an element without overwriting any that already exist. Many event handlers can be added to a single element. The removeEventListener() function makes it simple to remove an event listener.
Creating New Elements
const div = document.getElementById("div");
const p = document.createElement("p");
const text = document.createTextNode("This is a new paragraph.");
p.appendChild(text);
div.appendChild(p);
// or
const p = document.createElement("p");
p.innerHTML = "New Paragraph";
div.appendChild(p);
// or
div.innerHTML = "<p>New Paragraph</p>";
You must first create the element before appending it to an existing element to add a new element to the HTML DOM.
<div id="div1">Ā
<p id="p1">This is a paragraph.</p>Ā
<p id="p2">This is another paragraph.</p>
</div>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const element = document.getElementById("div1");
const child = document.getElementById("p1");
element.insertBefore(para, child);
You can use the insertBefore() method to insert before a particular element.
document.getElementById("div").remove()
Use the remove() or removeChild() methods to remove an HTML element.
Other JavaScript properties, methods and objects include math, date, array methods and so on. The links below will provide you with additional information.