When the browser loads an HTML file, it creates a representation of
the page called DOM: Document Object Model.
<!DOCTYPE html>
<html>
<head>
<title>Document demo</title>
</head>
<body>
<p>
This file loaded:
</p>
<div id="timestamp">
</div>
</body>
</html>
The DOM lets JavaScript communicate with and change a page's HTML.
Basic method is to
- Search for HTML DOM Element
- Do someting
<script>
var mytimestamp = document.getElementById("timestamp"); // PART1: Search for DOM
mytimestamp.innerHTML = Date(); // PART2: Do stuff
mytimestamp.style.backgroundColor = "yellow";
</script>
Methods used to search for HTML Elements:
document.getElementById(); // returns a single element
document.getElementsByTagName(); // returns an array
document.getElementsByClassName(); // returns an array
document.querySelector() // returns a single element
document.querySelectorAll() // returns an array
Once you have the HTML DOM Object, it allows you access to CSS, the
text inside, and to attributes amongst other things using the dot
notation
Example of javascript accessing attributes:
<img id="myImage" src="smiley.gif">
...
...
<script>
var mysrc = document.getElementById("myImage");
mysrc.src = "sadface.jpg";
</script>
<img id="myImage" src="smiley.gif">
...
...
<script>
document.getElementById("myImage").src = "sadface.jpg";
</script>
See [
HTML DOM@W3schools]