DOCUMENT OBJECT MODEL
Joseph Woyshner
What?
- API for manipulating HTML, XML and SVG documents.
- structured, organized reference of data content
- usually in the form of a hierarchical tree, but not necessarily
- broken out as "nodes" and objects with properties and methods.
- API typically manipulated through Javascript, but not necessarily.
MORE WHAT?
DOM LEVELS
- 0
- 1
- 2
- 3
Event handling
- Capture - first path
- Bubble - second path
Issues
Various browsers across the era of WWW
have implemented the DOM in different ways.
W3C group offers governance which provides a body of standards
for modern browsers to adhere to
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
jQuery handling various browser implementations for
preventing default event propagation.
WHERE??
window.document === document
> true
The document is at the top of the DOM hierarchy (root object)
Each webpage, or tab, has its own window object.
The window is actually part of the BOM
which interfaces with the DOM.
Performant
WEB DEVELOPMENT
Manipulating the DOM in Javascript is relatively expensive in comparison to other actions.
Scroll sideways!
Cache your selectors as variables
$element = $('.myClass');
$element.html("hello world");
$element.css("color":"red");
...and chain methods where applicable
$element
.html("hello world")
.css("color","red");
Avoid extra DOM traversal!!!
BAD
$.each(json_payload, function(){
$('table tbody').append(
'<tr>' +
'<td>'+this.name+'</td>'
'</tr>'
);
});
GOOD
var $reference = $('table tbody');
var htmlToInsert = "";
$.each(json_payload, function(){
$htmlToInsert +=
'<tr>' +
'<td>'+this.name+'</td>'
'</tr>'
);
});
$reference.append(htmlToInsert);
Another example...
event delegation
BAD
$('tr button').click(function(event){
do something...
});
iterates over each tr and applies click event handler. not efficient
$('tr ').on('click','button',function(event){
do something...
});
GOOD
tr is the reference container
DOCUMENT OBJECT MODEL
By Joe Woyshner
DOCUMENT OBJECT MODEL
- 249