As an HTML attribute
<body>
</body>
As a method
window.onclick = myFunction();
major drawback of using methods:
addEventListener
Document Object Model (DOM)
DOM as document tree
Accessing DOM nodes
– The document object in the DOM identifies the
page itself.
– The document object comes with a number of
standard properties and methods for accessing
collections of elements.
– The document object comes with a number of
built-in properties containing information about
the document.
getElementById()
var foo = document.getElementById( “beginner” ).innerHTML;
* the statement says to look on the page (document), find the
element that has the id value “beginner”, find the HTML content
within that element (innerHTML), and save those contents to a
variable (foo).
getElementsByTagName()
– document.getElementsByTagName(“p”) returns every
paragraph on the page, wrapped in something called a
collection or nodeList, in the order they appear in the
document from top to bottom.
– nodeLists behave much like arrays.
- To access specific paragraphs in the nodeList, we reference
them by their index, just like an array.
getElementById()
– <imgsrc=”photo.jpg” alt=”” id=”lead-photo”>’
– var photo = document.getElementById(“lead-photo”);
getAttribute()
– <imgsrc=”stratocaster.jpg” alt=”electric guitar” id=”lead
image”>
– var bigImage = document.getElementById(“lead-image”);
– alert( bigImage.getAttribute(“src”) ); // Alerts
“stratocaster.jpg”.
getElementsByClassName()
– this allows you to access nodes in the document based
on the value of a class attribute.
* <div class="example">Element1</div>
<div>Element2</div>
<script>
const collection = document.getElementsByClassName("example");
collection[0].innerHTML = "Hello World!";
</script>