scripts. • Scripts are attached to events. • Changes in DOM yield page re-painting.
Diagramma. Douglas Crockford,. The theory of DOM, http://yuiblog.com/assets/.
JavaScript and the browser DOM Web Technologies I Krišs Rauhvargers, 2012
DOM • A JavaScript interpreter is built into modern browsers • The interpreter has access to document object model (DOM) of the browser: – it imitates JavaScript object interface, – all objects are proxies – by altering their properties, things change on screen • body.style.backgroundColor="red";! • //now document background is red
• Every time you change a visual property, browser re-paints all the page
Collaboration of scripts and browser • Every item on the page has its place in DOM. • Each DOM element can be changed by scripts • Scripts are attached to events • Changes in DOM yield page re-painting Diagramma Douglas Crockford, The theory of DOM, http://yuiblog.com/assets/ crockford/theory.zip
What's inside the dom • Initially, DOM model is constructed from HTML document which is loaded, something that resembles this. • The global document object allows accessing parts of HTML document. document.head!
document.body!
4
Additional things in the DOM. • Browser environment contains a lot more than HTML document – user interaction – current location – information about display device ...
• "The beginning" is the window object whose properties – document is just one of those properties
document structure of actual html document
window
loca2on current URL (read/write) screen display device (resolu5on, color depth, posi5on) navigator user agent (version, language support)
history (browsing history)
localStorage local "database" at the user agent (modern browsers)
Accessing DOM from scripts • window object is available everywhere in JavaScript code • document, location, screen, ... are attributes (properties) of window object! window.location = "http://asdf.com";! window.document.title = "Another document";!
• window object corresponds to "global" object of jasvascript – all "global variables" are actually properties of window. – you can add your own properties to window object: • var test="test";! • alert(window.test)!
– functions which seem to be global, are actually methods of window object • alert() →window.alert()
DOM standard • Originally meant for XML structure – XHTML and HTML are just one of uses – Many parts of dom are not relevant to HTML
• Different DOM standards: – DOM level 1: • http://www.w3.org/TR/DOM-Level-1/ • http://www.xml.com/1999/07/dom/xml_dom.gif
– DOM level 2: • http://www.w3.org/TR/DOM-Level-2-Core/
– DOM level 3: • http://www.w3.org/TR/DOM-Level-3-Core/core.html 7
DOM support in browsers • Typically, only partial support: – http://en.wikipedia.org/wiki/ Comparison_of_layout_engines_(Document_Object_Model)
• Many features of DOM standard are not implemented or have specific implementations • Additional features are added which are not part of DOM standard – e.g., .innerHTML attribute 8
FINDING ELEMENTS IN DOM AND WORKING WITH THEM 9
What to do with the DOM? • Typically, you need to change some element in the page. • You know where it was in HTML, but how to find it in the DOM tree?
Finding a known element • If the required element is assigned an ID, you can use the document.getElementById method to find it. – object hierarchy is ignored – document.getElementById(some_id) – if element with such ID is not found, returns null
• document is a global object and is available just as document starts loading 11
GetElementById example !
! ! var article = document.getElementById("article");! article.style.border="1px solid red";! 12
Ways to select multiple elements • These methods return an array of matching elements (which may be empty) – element.getElementsByTagName(tag)! • by the HTML element tag name, e.g. all DIV elements
– document.getElementsByName(name)! • by "name" attribute assigned to element, useful on input elements
• In modern browsers – document.getElementsByClassName(class)! •
foo
foofoo
– document.querySelectorAll(selector) • works like a CSS selector 13
WORKING WITH DOM SEARCH RESULTS 14
DOM node attributes • Once you find the required element, you can change its properties – properties pf DOM object match attributes of original HTML element – for instance • DOM node of an
element has attribute .src – once you change it, another image is loaded
15
Example: IMG attributes • Img element has at least these properties – – – – – – – – – – –
align alt border height hspace id isMap src useMap vspace width
'none', 'top', 'left', ... string integer (pixels) integer (pixels) integer (pixels) string boolean url url integer (pixels) integer (pixels)
Slide from Douglas Crockford, The theory of DOM,
http://yuiblog.com/assets/
crockford/theory.zip
What attributes and methods to use? • Each HTML element has its own attributes, each DOM object has different things you can do with it. • It is best to lookup HTML DOM reference: – Googling by required keyword + "object", e.g. "div object" – Mozilla Developer Network https://developer.mozilla.org/en/ Gecko_DOM_Reference#HTML_interfaces
– or elsewhere e.g., W3Schools documentation http://www.w3schools.com/HTMLDOM/dom_obj_body.asp
Changing element "outfit" by setting another CSS clsas • CSS class can be changed by setting className attribute
... document.getElementById("ku").className="fgh"
• className contains all CSS classes, separated by a space • After the browser re-paints the document, the element will have the properties of assigned class
Changing "outfit" by assigning individual properties • to set individual design properties, you can use the "style" attribute of any DOM element – ...object.style.attribute.... e.g. document.body.style.color="red"
• Attribute names similar to CSS property names, but – 1) without dashes; – 2) using camelCase notation; • border-bottom -> borderBottom document.body.style.borderBottom="1px solid red";!
19
Attribute titles CSS • • • • • •
background-color border-radius font-size list-style-type word-spacing z-index
JavaScript • • • • • •
backgroundColor borderRadius fontSize listStyleType wordSpacing zIndex Slide from Douglas Crockford, The theory of DOM
WORKING WITH ELEMENT HIERARCHY 21
Accessing children of some element • Each node has childNodes collection • It returns all direct ancestors as sorted array – document.body.childNodes[1]
Viss nav tik slikti!
viss mums būs ok..
body body.childNodes
h1 p img
Specific children of element • firstChild – first item in childNodes collection
• lastChild – last item in childNodes collection
• Accessing firstChild and lastChild is "cheaper", does not have to load all children.
Viss nav tik slikti!
viss mums būs ok..
body body.firstChild
h1
body.lastChild
p img
Sibling nodes • Each node has nextSibling and previousSibling attributes • It returns next node in the same level • This includes empty text nodes as well – Text nodes appear from spaces between elements in HTML code
• http://www.w3schools.com/dom/dom_nodetype.asp
Viss nav tik slikti!
viss ok.. H1 and P There is a nmums ewline būs between
body h1 h1Obj.nextSibling? h1Obj.nextSibling!
"\n" p img
Example of nextSibling traversal function demo(){! var node = window.document.body.firstChild;! var ret = "";! while (node !=null){! //1 = "element node"! if ( node.nodeType==1 ) {! ret += node.nodeName + "\n";! }! node = node.nextSibling;! }! alert(ret);! }! 25
Walking up the dom • Each node has a parentNode – returns the containing element
Viss nav tik slikti!
viss mums būs ok..
h1Obj.parentNode
div h1 p
img
CREATION OF NEW ELEMENTS 27
Creation of new elements • New elements can only be created by the document object: – createElement – createTextNode • document.createElement("type_of_element")
• for instance var logo = document.createElement("IMG"); //type of logo is "HTMLImageElement" logo.src="http://www.lu.lv/logo.gif";
– The new object is not yet included in the document – Hence it is not visible yet
28
Adding the new element to DOM tree • New nodes are added to DOM tree by – parent.appendChild(...) – parent.insertBefore(newNode,oldNode)
• For instance var logo = document.createElement("IMG"); logo.src="http://www.lu.lv/logo.gif"; var intro = document.getElementById("intro") intro.appendChild(logo); 29
Creating inline text • To create inline text (e.g. text to put in A element between tags) document.createTextNode("text to show") • For instance, to create a paragraph with text: • var para = document.createElement("P"); var paraText = document .createTextNode("Sample text");
para.appendChild(paraText); document.body.appendChild(para);
Using innerHTML attribute • InnerHTML is a non-standard (but widely implemented) method of creating HTML content • document.getElementByID("test") .innerHTML="
klikšķini te";
• It uses browser's HTML parser to create the required object structure • Probably works faster than createElement(...), appendChild(...)
Replacing and deleting elements node.appendChild(new) //adding elements before other elements node.insertBefore(new, sibling) //replacing old elements with new ones node.replaceChild(new, old) //suicidal replacement old.parentNode.replaceChild(new, old)
//deleting some node old.parentNode.removeChild(old)