This document discusses DOM (Document Object Model) and events in JavaScript. It covers DOM node retrieval, the document tree structure, child, sibling and parent node relationships, DOM manipulation methods like appendChild and innerHTML, event handling and the bubbling and default behaviors of events.
4. Document Tree Structure
<html>
<body>
<h1>Heading 1</h1>
<p>Paragraph.</p>
<h2>Heading 2</h2>
<p>Paragraph.</p>
</body>
</html>
#text
H1
P
H2
BODY
#document
HTML
HEAD
#text
P
#text
#text
5. child, sibling, parent
BODY
H1 P H2
#text
#text
P
#text #text
lastChild
lastChild
lastChild
lastChild
lastChild
firstChild
firstChild
firstChild
firstChild
firstChild
6. child, sibling, parent (Con.)
BODY
H1 P H2
#text
#text
P
#text #text
lastChild
lastChild
lastChild
lastChild
lastChild
firstChild
firstChild
firstChild
firstChild
firstChild
nextSibling nextSibling nextSibling
previousSibling previousSibling previousSibling
14. innerHTML
•The W3C standard does not provide access to the HTML
parser
•All browsers implement Microsoft's innerHTML property
•node.innerHTML = “<p>this is text</p>”;
15. Which Way is Better?
•It is better to build or clone elements and append them to the
document?
•Or is it better to complile an HTML text and use innerHTML to
realize it?
•Favor clean code and easy maintenance
•Favor performance only in extreme cases
16. Event
•The browser has an event-driven, single-threaded,
asynchronous programming model
•Events are targeted to particular nodes
•Event cause the invocation of event handler functions
17. Mouse Event
The target is the topmost (z-index) node containing the
cursor:
•click
•dblclick
•mousedown
•mousemove
•mouseout
•mouseover
•mouseup
18. Input Event
The target is the node having focus:
•blur
•change
•focus
•keydown
•keyup
•reset
•submit
19. Event Handler
•Classic
– node[“on” + type] = handler;
•Microsoft
– node.attachEvent(“on” + type, handler);
•W3C
– node.addEventListener(type, handler, false);
var handler = function(e) {
e = e || event;
var target = e.target || e.srcElement;
…
}
20. Bubbling
Bubbling means that the event is given to the target, and then
its parent, and so on until the event is canceled.
21. Why Bubble?
•Suppose you have 100 draggable objects
•You could attach 100 sets of event handlers to those
objects
•Or you could attach one set of event handlers to the
container of the 100 objects
22. Cancel Bubbling
•Cancel bubbling to keep the parent nodes from seeing th
event:
e.cancelBubble = true;
If(e.stopPropagation) {
e.stopPropagation();
}
23. Prevent Default Action
•An event handler can prevent a browser action associated with
the event (such as submitting a form):
e.returnValue = false;
If(e.preventDefault) {
e.preventDefault();
}
Return false;