DOM & Event in JavaScript:
DOM & Event in JavaScript:
Note: JavaScript can be used to manipulate the DOM of a Page dynamically to add, delete and modify elements.
DOM Tree: The DOM represents a document as a tree structure. HTML elements become interrelated notes in the Tree.
All those nodes in the tree have some kind of relations among each other. Nodes can have child Nodes. Nodes on the same tree level are called siblings. For example, consider the following structure.
Example:
<html>
<title> has two children </title>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
It is important to understand the relationships between elements in on HTML document in Order to be able to manipulate them with JavaScript
The Document Object: This is a Predefined document Object in javascript which can be used to access all elements on the Dom in other words,the document object is the owner(or root) of all objects in your webpage.
so if you want an object in an HTML page, you always start with accessing the Document Object.
Note: The inner HTML Property can be used on almost all HTML documents to change its content.
Selecting Elements: All HTML elements are objects.object and as we know object has properties and methods.
The document object has Methods that allow you to select the desired HTML element. the three methods are most commonly used for find element by id
Selecting HTML elements:
document.getElementById(id)
document.getElementByIdClassName(name)
document.getElementByTagName(name)
in the Example below, the GetElementById method is used to select the element with id = “demo” and change its content
var elem = document.getElementById(“demo”);
elem.innerHTML = “HelloWorld !”;
The example above assumes that the HTML Contains an element with
id = “demo”,
Example: <div id = “demo”> </div>
Selecting Elements: The getElementsByClassName() method returns a collection of all elements in the document with the specified class name.
Example: if our HTML page, contained three element with class = “demo”, the following code would return all those elements as an array
var arr =
document.getElementsByClassName(“demo”);
//accessing the Second elements
arr[1].innerHTML = “Hi’;
Similarly, the getElementsNyTagName method returns all of the elements of the specified tag name as an array.
Example:
<P> hi <P>
<P> hello <P>
<P> hi <P>
<Script>
var arr = document.getElementsByTagName(“P”);
for(var x = 0; x<arr.lenght; x++){
arr[x].innerHTML = “Hi there”;
}
the script will result in the following HTML
<P> Hi There <P>
<P> Hi There <P>
<P> Hi There <P>
Technical content writer with data scientist, artificial intelligence, programming language, database. He has a bachelor’s degree in IT and a certificate in digital marketing, Digital transformation web development android app development He has written for website like Boomi techie, tech mantra, information hub, Tech all