The Document Object Model (DOM)
Selection Methods
Classic
• getElementById()
• getElementsByTagName()
• getElementsByClassName() Newer
• querySelector() and
• querySelectorAll()
51
The Document Object Model (DOM)
Selection Methods
Reviews
var node = document.getElementById(“latest”);
By Ricardo on 2016-05-23
Easy on the HDR buddy.
By Susan on 2016-11-18
I love Central Park.
var list1 = document.getElementsByTagName(“div”);
var list2 = document.getElementByClassName(“comment”);
52
The Document Object Model (DOM)
Query Selector
querySelectorAll(“nav ul a:link”)
Comments as of November 15, 2012
By Ricardo on September 15, 2012
Easy on the HDR buddy.
By Susan on October 1, 2012
I love Central Park.
53
The Document Object Model (DOM)
Element Node Object
Element Node object represents an HTML element in the hierarchy, contained between the opening <> and closing > tags for this element. Every node has
• classList
• className • Id
• innerHTML • Style
• tagName
54
The Document Object Model (DOM)
More common (not universal) properties
• href
• name • src
• value
55
Modifying the DOM
56
Modifying the DOM
Changing an Element’s Style
…
var node = document.querySelector(“main div”);
node.className = “yellowish”;
This replaces the existing class specification with
this one. Thus the
no longer has the box class
node.classList.remove(“yellowish”); node.classList.add(“box”);
Removes the specified class specification and adds the box class
node.classList.add(“yellowish”);
Adds a new class to the existing class specification
node.classList.toggle(“hide”); node.classList.toggle(“hide”);
If it isn’t in the class specification, then add it If it is in the class specification, then remove it
11 22
33
44 55
Equivalent to:
Modifying the DOM
Changing an Element’s Content
document.getElementById(“here”).innerHTML = “foobar“;
1. Create a new Node
2. Add Node to an element in the DOM
59
Events
60
Events
JavaScript event is an action that can be detected by JavaScript
• Many of them are initiated by user actions
• some are generated by the browser itself.
We say that an event is triggered and then it is handled by JavaScript functions
61
Events
Event-Handling Approaches – Inline Hook
HTML document using the inline hooks
inline.js
function validate(node) {
…
}
function check(node) {
… }
function highlight(node) {
…
}
…