HTML DOM
{tocify} $title={Table of Contents}
When HTML document is loaded, the browser creates an HTML Document Object Model or HTML DOM.
What is the DOM?
- The DOM is created by the browser when an HTML document is loaded.
- Whit the object model, JavaScript gets all the power it needs to create dynamic HTML.
- JavaScript can change all the HTML elements in the page.
- JavaScript can change all the HTML attributes in the page.
- JavaScript can change all the CSS style in the page.
- JavaScript can remove existing HTML elements and attributes.
- JavaScript can add new HTML elements and attributes.
- JavaScript can create new HTML events in the page.
Example:
The following example change the background color of the <div> element white the id=”test’:
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>PoorWebDev</title>
</head>
<body>
<div id="test"></div>
<button id="change">Click to change color</button>
</body>
</html>
JavaScript Code:
var color = document.getElementById("test");
var test = document.getElementById("change");
test.addEventListener("click", function(){
color.style.background="lightgreen";
});
What is the use of DOM ?
It allows a language (JavaScript) to manipulate, structure, and style your website.
HTML DOM Structure:
Top DOM Events:
- Mouse events (Mouse Event ): mousedown, mouseup, click, dbclick.
- touch events (Touch Event ): touchstart, touchmove, touchend, touchcancel.
- keyboard events ( Keyboard Event ): keydown, keyup, keypress.
- form events : focus, blur, change.
DOM Manipulation.
It defines the logical structure of documents and the way a document is accessed and manipulated. The DOM is designed to be used with any programming language.
DOM Selectors.
We can select any element from the DOM tree using document object.
Why do we select elements?
- To get their content.
- To change their content.
- To style them.
- To get or change their attribute.
- To remove them.
Select an element by ID.
The document.getElementById() selects the element whose id attribute matches the specified string.
<div id="test"></div>
<script>
document.getElementById("test");
</script>
Select an element by Class Name.
The document,getElementByClassName(); select all elements with the given class name.
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<script>
document.getElementByClassname("test");
</script>
Select elements by Tag Name.
The document.getElementByTagName(); select all the all the given tag name.
<h1 class="test">1</h1>
<p class="test">2</p>
<h1 class="test">3</h1>
<script>
document.getElementByTagName("h1");
</script>
Related Posts:
- Introduction Html Click
- JavaScript Introduction Click
- Basic CSS Click
Examples:
Click hear:-simple Calculator using JavaScript & html