Document Object Model ( DOM ) in Java Script
The HTML DOM (Document Object Model) document object is the owner of all other objects in your web page.
The Virtual DOM
In React, for every DOM Object, there is a corresponding "Virtual DOM Object" A virtual DOM object is a representation of a DOM object, like a lightweight copy.
A virtual DOM object has the same properties as a real DOM Object, but it lacks the real thing`s power to directly change what`s on the screen.
Virtual DOM , and its usages
- Prevents Unnecessary Modifications
- It will only repairs updated elements
- It will Groups together repairs
Get Element By Class Name
<script> var main = document.getElementsByClassName('main') console.log(main); </script>
The HTML DOM Document Object
The document object represents your web page.
If you want to access any element in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.
Finding HTML Elements
Method | Description |
---|---|
document.getElementById(id) | Find an element by element id |
document.getElementsByTagName(name) | Find elements by tag name |
document.getElementsByClassName(name) | Find elements by class name |
<html lang="en"> <head> <script>
document.getElementById("mesage");
document.getElementsByTagName('h1');
</script> </head> <body> <div id="mesage"> the quick brown fox jumps over the lazy dog </div> <div class="txt"> <h1>demo</h1> <p>the quick brown fox jumps over the lazy dog</p> </div>
</body> </html>
Design Date() Method using DOM
With the HTML DOM, JavaScript can access and change all the elements of an HTMLdocument. Here you can see , i assigned css to element
<style>
.para{ color: white; font-weight: bold; background-color: darkcyan; padding: 10px; width: 250px; }
</style>
Here can see, to generate date method, i used DOM ..
Changing HTML Elements
Property | Description |
---|---|
element.innerHTML = new html content | Change the inner HTML of an element |
element.attribute = new value | Change the attribute value of an HTML element |
element.style.property = new style | Change the style of an HTML element |
Method | Description |
element.setAttribute(attribute, value) | Change the attribute value of an HTML element |
<body> <p id="text">Hello World!</p>
<script> document.getElementById("text").innerHTML = "New Text here"; </script>
</body>
Changing the style of HTML Element
<body>
<p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color = "blue"; </script> </body>
Adding and Deleting Elements
Method | Description |
---|---|
document.createElement(element) | Create an HTML element |
document.removeChild(element) | Remove an HTML element |
document.appendChild(element) | Add an HTML element |
document.replaceChild(new, old) | Replace an HTML element |
document.write(text) | Write into the HTML output stream |