SlideShare a Scribd company logo
CS142 Lecture Notes - DOM
Document Object Model
(DOM)
Mendel Rosenblum
CS142 Lecture Notes - DOM
Browser JavaScript interface to HTML document
● HTML document exposed as a collection of JavaScript objects and methods
The Document Object Model (DOM)
● JavaScript can query or modify the HTML document
● Accessible via the JavaScript global scope, aliases:
window
this (When not using 'use strict';)
CS142 Lecture Notes - DOM
DOM hierarchy
● Rooted at window.document (html tag)
● Follows HTML document structure
window.document.head
window.document.body
● Tree nodes (DOM objects) have tons (~250) of properties, most private
Objects (representing elements, raw text, etc.) have a common set of
properties and methods called a DOM "Node"
CS142 Lecture Notes - DOM
DOM Node properties and methods
● Identification
nodeName property is element type (uppercase: P, DIV, etc.) or #text
● Encode document's hierarchical structure
parentNode, nextSibling, previousSibling, firstChild, lastChild.
● Provide accessor and mutator methods
E.g. getAttribute, setAttribute methods, etc..
CS142 Lecture Notes - DOM
<p>Sample <b>bold</b> display</p>
nodeName: P
nodeType: 1 (Element)
nodeName: #text
nodeType: 3 (Text)
nodeValue: "Sample "
firstChild
nodeName: #text
nodeType: 3 (Text)
nodeValue: " display"
lastChild
nodeName: B
nodeType: 1
nextSibing
previousSibing
nextSibing
previousSibing
parentNode
parentNode
parentNode
nodeName: #text
nodeType: 3 (Text)
nodeValue: "bold"
parentNode
firstChild
lastChild
CS142 Lecture Notes - DOM
Accessing DOM Nodes
● Walk DOM hierarchy (not recommended)
element = document.body.firstChild.nextSibling.firstChild;
element.setAttribute(…
● Use DOM lookup method. An example using ids:
HTML: <div id="div42">...</div>
element = document.getElementById("div42");
element.setAttribute(…
● Many: getElementsByClassName(), getElementsByTagName(), …
○ Can start lookup at any element:
document.body.firstChild.getElementsByTagName()
CS142 Lecture Notes - DOM
More commonly used Node properties/methods
● textContent - text content of a node and its descendants
Previous slide example: P Node textContext is "Sample bold display"
● innerHTML - HTML syntax describing the element's descendants.
Previous slide example: P Node innerHTML is "Sample <b>bold</b> display"
● outerHTML - similar but includes element "<p>Sample <b>bold</b> display</p>"
● getAttribute()/setAttribute() - Get or set the attribute of an element
CS142 Lecture Notes - DOM
Common DOM mutating operations
● Change the content of an element
element.innerHTML = "This text is <i>important</i>";
Replaces content but retains attributes. DOM Node structure updated.
● Change an <img tag src attribute (e.g. toggle appearance on click)
img.src="newImage.jpg";
● Make element visible or invisible (e.g., for expandable sections, modals)
Invisible: element.style.display = "none";
Visible: element.style.display = "";
CS142 Lecture Notes - DOM
DOM and CSS interactions
● Can update an element's class
element.className = "active";
● Can update element's style
element.style.color = "#ff0000"; // Not preferred way!
● Can also query DOM by CSS selector
document.querySelector() and document.querySelectorAll()
CS142 Lecture Notes - DOM
Changing the Node structure
● Create a new element (can also cloneNode() an existing one)
element = document.createElement("P");
or
element = document.createTextNode("My Text");
● Add it to an existing one
parent.appendChild(element);
or
parent.insertBefore(element, sibling);
● Can also remove Nodes: node.removeChild(oldNode);
● But, setting innerHTML can be simpler and more efficient.
CS142 Lecture Notes - DOM
More DOM operations
● Redirect to a new page
window.location.href = "newPage.html";
Note: Can result in JavaScript script execution termination
● Communicating with the user
console.log("Reached point A"); // Message to browser log
alert("Wow!"); confirm("OK?"); // Popup dialog
CS142 Lecture Notes - DOM
DOM's Coordinate System
● The screen origin is at the upper left; y increases as you go down
● The position of an element is determined by the upper-left outside corner of
its margin
● Read location with element.offsetLeft, element.offsetTop
● Coordinates are relative to element.offsetParent, which is not necessarily
the same as element.parentNode
CS142 Lecture Notes - DOM
DOM Coordinates
X
Y
div1
div2
offsetWidth
offsetTop
offsetLeft
offsetHeight
offsetLeft
offsetTop
div3
offsetParent
offsetParent
<div class="div1"><div class="div2"><div class="div3"></div></div>/</div>
CS142 Lecture Notes - DOM
Positioning elements
● Normally elements are positioned automatically by the browser as part of the
document
● To pull an element out of the document flow and position it explicitly:
element.style.position = "absolute"; // anything but "static"
element.style.left = "40px";
element.style.top = "10px";
"absolute" - the element no longer occupies space in the document flow.
● The origin inside an offsetParent (for positioning descendants) is just inside
the upper-left corner of its border.
CS142 Lecture Notes - DOM
Positioning context
● Each element has an offsetParent (some ancestor element).
● When an element is positioned, coordinates such as element.style.left
are relative to its offsetParent.
● Default offsetParent is the <body> element.
● Some elements define a new positioning context:
○ position CSS attribute is absolute (element is explicitly positioned)
○ position CSS attribute is relative (element is positioned automatically by the browser in
the usual way)
○ This element will become the offsetParent for all its descendents (unless overridden by
another positioning context)
CS142 Lecture Notes - DOM
Positioning Children
Parent margin
Parent border
Parent padding
Child margin
Child border
top/offsetTop
left/offsetLeft
CS142 Lecture Notes - DOM
Element dimensions
● Reading dimensions: element.offsetWidth and element.offsetHeight
Include contents, padding, border, but not margin
● Updating dimensions: element.style.width and element.style.height
CS142 Lecture Notes - DOM
Positioning
<body>
<div id="div1">
<p>div1</p>
</div>
#div1 {
width: 50px;
height: 200px;
background: #ffe0e0;
}
CS142 Lecture Notes - DOM
Positioning
…
<div id="div2">
<p>div2</p>
<div id="div2-1">
<p>div2-1</p>
</div>
</div>
#div2 {width: 300px; height:
200px; position: relative;
background: #d0e0ff;}
#div2-1 {width: 150px; height:
80px; position: absolute;
top: 50px; left: 100px;
background: #d0e0ff;}
CS142 Lecture Notes - DOM
Positioning
...
<div id="div3">
<p>div3</p>
<div id="div3-1">
<p>div3-1</p>
</div>
</div>
#div3 {width: 300px; height:
200px; background: #ffffe0;}
#div3-1 {width: 150px; height:
80px; position: absolute; top:
50px; left: 100px; background:
#ffffe0;}

More Related Content

Similar to DOM.pdf

Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
GOPAL BASAK
 
jquery.ppt
jquery.pptjquery.ppt
jquery.ppt
HamnaGhani1
 
Part 7
Part 7Part 7
Part 7
NOHA AW
 
Document object model
Document object modelDocument object model
Document object model
Amit kumar
 
FYBSC IT Web Programming Unit III Document Object
FYBSC IT Web Programming Unit III  Document ObjectFYBSC IT Web Programming Unit III  Document Object
FYBSC IT Web Programming Unit III Document Object
Arti Parab Academics
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in Components
Anton Ivanov
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
Jennifer Estrada
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Seble Nigussie
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
Tudor Barbu
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
chomas kandar
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
chomas kandar
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Dom date and objects and event handling
Dom date and objects and event handlingDom date and objects and event handling
Dom date and objects and event handling
smitha273566
 
Web components
Web componentsWeb components
Web components
Gil Fink
 
Custom elements - An alternate Render API for decoupled Drupal
Custom elements - An alternate Render API for decoupled DrupalCustom elements - An alternate Render API for decoupled Drupal
Custom elements - An alternate Render API for decoupled Drupal
nuppla
 
Client Side Technologies
Client Side TechnologiesClient Side Technologies
Client Side Technologies
Anirban Majumdar
 
Document Object Model
Document Object ModelDocument Object Model
ENIB 2015 2016 - CAI Web S02E01- Côté Navigateur 3/3 - Web Components avec Po...
ENIB 2015 2016 - CAI Web S02E01- Côté Navigateur 3/3 - Web Components avec Po...ENIB 2015 2016 - CAI Web S02E01- Côté Navigateur 3/3 - Web Components avec Po...
ENIB 2015 2016 - CAI Web S02E01- Côté Navigateur 3/3 - Web Components avec Po...
Horacio Gonzalez
 
Polymer
PolymerPolymer
Polymer
LearningTech
 
Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
Mohammad Imam Hossain
 

Similar to DOM.pdf (20)

Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 
jquery.ppt
jquery.pptjquery.ppt
jquery.ppt
 
Part 7
Part 7Part 7
Part 7
 
Document object model
Document object modelDocument object model
Document object model
 
FYBSC IT Web Programming Unit III Document Object
FYBSC IT Web Programming Unit III  Document ObjectFYBSC IT Web Programming Unit III  Document Object
FYBSC IT Web Programming Unit III Document Object
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in Components
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
Dom date and objects and event handling
Dom date and objects and event handlingDom date and objects and event handling
Dom date and objects and event handling
 
Web components
Web componentsWeb components
Web components
 
Custom elements - An alternate Render API for decoupled Drupal
Custom elements - An alternate Render API for decoupled DrupalCustom elements - An alternate Render API for decoupled Drupal
Custom elements - An alternate Render API for decoupled Drupal
 
Client Side Technologies
Client Side TechnologiesClient Side Technologies
Client Side Technologies
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
ENIB 2015 2016 - CAI Web S02E01- Côté Navigateur 3/3 - Web Components avec Po...
ENIB 2015 2016 - CAI Web S02E01- Côté Navigateur 3/3 - Web Components avec Po...ENIB 2015 2016 - CAI Web S02E01- Côté Navigateur 3/3 - Web Components avec Po...
ENIB 2015 2016 - CAI Web S02E01- Côté Navigateur 3/3 - Web Components avec Po...
 
Polymer
PolymerPolymer
Polymer
 
Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
 

More from stephanedjeukam1

HTTP.pdf
HTTP.pdfHTTP.pdf
Database.pdf
Database.pdfDatabase.pdf
Database.pdf
stephanedjeukam1
 
HTML.pdf
HTML.pdfHTML.pdf
CodeInjection.pdf
CodeInjection.pdfCodeInjection.pdf
CodeInjection.pdf
stephanedjeukam1
 
Express.pdf
Express.pdfExpress.pdf
Express.pdf
stephanedjeukam1
 
Input.pdf
Input.pdfInput.pdf
Input.pdf
stephanedjeukam1
 
FrontEnd.pdf
FrontEnd.pdfFrontEnd.pdf
FrontEnd.pdf
stephanedjeukam1
 
CSS.pdf
CSS.pdfCSS.pdf
DOSAttacks.pdf
DOSAttacks.pdfDOSAttacks.pdf
DOSAttacks.pdf
stephanedjeukam1
 
0000 Syllabus.pdf
0000  Syllabus.pdf0000  Syllabus.pdf
0000 Syllabus.pdf
stephanedjeukam1
 
Events.pdf
Events.pdfEvents.pdf
Events.pdf
stephanedjeukam1
 

More from stephanedjeukam1 (11)

HTTP.pdf
HTTP.pdfHTTP.pdf
HTTP.pdf
 
Database.pdf
Database.pdfDatabase.pdf
Database.pdf
 
HTML.pdf
HTML.pdfHTML.pdf
HTML.pdf
 
CodeInjection.pdf
CodeInjection.pdfCodeInjection.pdf
CodeInjection.pdf
 
Express.pdf
Express.pdfExpress.pdf
Express.pdf
 
Input.pdf
Input.pdfInput.pdf
Input.pdf
 
FrontEnd.pdf
FrontEnd.pdfFrontEnd.pdf
FrontEnd.pdf
 
CSS.pdf
CSS.pdfCSS.pdf
CSS.pdf
 
DOSAttacks.pdf
DOSAttacks.pdfDOSAttacks.pdf
DOSAttacks.pdf
 
0000 Syllabus.pdf
0000  Syllabus.pdf0000  Syllabus.pdf
0000 Syllabus.pdf
 
Events.pdf
Events.pdfEvents.pdf
Events.pdf
 

Recently uploaded

一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
thezot
 
Bengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal BrandingBengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal Branding
Tarandeep Singh
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
k4ncd0z
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
Paul Walk
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
Donato Onofri
 
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
rtunex8r
 
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
APNIC
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
xjq03c34
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
davidjhones387
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
3a0sd7z3
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
APNIC
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
3a0sd7z3
 

Recently uploaded (12)

一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
 
Bengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal BrandingBengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal Branding
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
 
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
 
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
 

DOM.pdf

  • 1. CS142 Lecture Notes - DOM Document Object Model (DOM) Mendel Rosenblum
  • 2. CS142 Lecture Notes - DOM Browser JavaScript interface to HTML document ● HTML document exposed as a collection of JavaScript objects and methods The Document Object Model (DOM) ● JavaScript can query or modify the HTML document ● Accessible via the JavaScript global scope, aliases: window this (When not using 'use strict';)
  • 3. CS142 Lecture Notes - DOM DOM hierarchy ● Rooted at window.document (html tag) ● Follows HTML document structure window.document.head window.document.body ● Tree nodes (DOM objects) have tons (~250) of properties, most private Objects (representing elements, raw text, etc.) have a common set of properties and methods called a DOM "Node"
  • 4. CS142 Lecture Notes - DOM DOM Node properties and methods ● Identification nodeName property is element type (uppercase: P, DIV, etc.) or #text ● Encode document's hierarchical structure parentNode, nextSibling, previousSibling, firstChild, lastChild. ● Provide accessor and mutator methods E.g. getAttribute, setAttribute methods, etc..
  • 5. CS142 Lecture Notes - DOM <p>Sample <b>bold</b> display</p> nodeName: P nodeType: 1 (Element) nodeName: #text nodeType: 3 (Text) nodeValue: "Sample " firstChild nodeName: #text nodeType: 3 (Text) nodeValue: " display" lastChild nodeName: B nodeType: 1 nextSibing previousSibing nextSibing previousSibing parentNode parentNode parentNode nodeName: #text nodeType: 3 (Text) nodeValue: "bold" parentNode firstChild lastChild
  • 6. CS142 Lecture Notes - DOM Accessing DOM Nodes ● Walk DOM hierarchy (not recommended) element = document.body.firstChild.nextSibling.firstChild; element.setAttribute(… ● Use DOM lookup method. An example using ids: HTML: <div id="div42">...</div> element = document.getElementById("div42"); element.setAttribute(… ● Many: getElementsByClassName(), getElementsByTagName(), … ○ Can start lookup at any element: document.body.firstChild.getElementsByTagName()
  • 7. CS142 Lecture Notes - DOM More commonly used Node properties/methods ● textContent - text content of a node and its descendants Previous slide example: P Node textContext is "Sample bold display" ● innerHTML - HTML syntax describing the element's descendants. Previous slide example: P Node innerHTML is "Sample <b>bold</b> display" ● outerHTML - similar but includes element "<p>Sample <b>bold</b> display</p>" ● getAttribute()/setAttribute() - Get or set the attribute of an element
  • 8. CS142 Lecture Notes - DOM Common DOM mutating operations ● Change the content of an element element.innerHTML = "This text is <i>important</i>"; Replaces content but retains attributes. DOM Node structure updated. ● Change an <img tag src attribute (e.g. toggle appearance on click) img.src="newImage.jpg"; ● Make element visible or invisible (e.g., for expandable sections, modals) Invisible: element.style.display = "none"; Visible: element.style.display = "";
  • 9. CS142 Lecture Notes - DOM DOM and CSS interactions ● Can update an element's class element.className = "active"; ● Can update element's style element.style.color = "#ff0000"; // Not preferred way! ● Can also query DOM by CSS selector document.querySelector() and document.querySelectorAll()
  • 10. CS142 Lecture Notes - DOM Changing the Node structure ● Create a new element (can also cloneNode() an existing one) element = document.createElement("P"); or element = document.createTextNode("My Text"); ● Add it to an existing one parent.appendChild(element); or parent.insertBefore(element, sibling); ● Can also remove Nodes: node.removeChild(oldNode); ● But, setting innerHTML can be simpler and more efficient.
  • 11. CS142 Lecture Notes - DOM More DOM operations ● Redirect to a new page window.location.href = "newPage.html"; Note: Can result in JavaScript script execution termination ● Communicating with the user console.log("Reached point A"); // Message to browser log alert("Wow!"); confirm("OK?"); // Popup dialog
  • 12. CS142 Lecture Notes - DOM DOM's Coordinate System ● The screen origin is at the upper left; y increases as you go down ● The position of an element is determined by the upper-left outside corner of its margin ● Read location with element.offsetLeft, element.offsetTop ● Coordinates are relative to element.offsetParent, which is not necessarily the same as element.parentNode
  • 13. CS142 Lecture Notes - DOM DOM Coordinates X Y div1 div2 offsetWidth offsetTop offsetLeft offsetHeight offsetLeft offsetTop div3 offsetParent offsetParent <div class="div1"><div class="div2"><div class="div3"></div></div>/</div>
  • 14. CS142 Lecture Notes - DOM Positioning elements ● Normally elements are positioned automatically by the browser as part of the document ● To pull an element out of the document flow and position it explicitly: element.style.position = "absolute"; // anything but "static" element.style.left = "40px"; element.style.top = "10px"; "absolute" - the element no longer occupies space in the document flow. ● The origin inside an offsetParent (for positioning descendants) is just inside the upper-left corner of its border.
  • 15. CS142 Lecture Notes - DOM Positioning context ● Each element has an offsetParent (some ancestor element). ● When an element is positioned, coordinates such as element.style.left are relative to its offsetParent. ● Default offsetParent is the <body> element. ● Some elements define a new positioning context: ○ position CSS attribute is absolute (element is explicitly positioned) ○ position CSS attribute is relative (element is positioned automatically by the browser in the usual way) ○ This element will become the offsetParent for all its descendents (unless overridden by another positioning context)
  • 16. CS142 Lecture Notes - DOM Positioning Children Parent margin Parent border Parent padding Child margin Child border top/offsetTop left/offsetLeft
  • 17. CS142 Lecture Notes - DOM Element dimensions ● Reading dimensions: element.offsetWidth and element.offsetHeight Include contents, padding, border, but not margin ● Updating dimensions: element.style.width and element.style.height
  • 18. CS142 Lecture Notes - DOM Positioning <body> <div id="div1"> <p>div1</p> </div> #div1 { width: 50px; height: 200px; background: #ffe0e0; }
  • 19. CS142 Lecture Notes - DOM Positioning … <div id="div2"> <p>div2</p> <div id="div2-1"> <p>div2-1</p> </div> </div> #div2 {width: 300px; height: 200px; position: relative; background: #d0e0ff;} #div2-1 {width: 150px; height: 80px; position: absolute; top: 50px; left: 100px; background: #d0e0ff;}
  • 20. CS142 Lecture Notes - DOM Positioning ... <div id="div3"> <p>div3</p> <div id="div3-1"> <p>div3-1</p> </div> </div> #div3 {width: 300px; height: 200px; background: #ffffe0;} #div3-1 {width: 150px; height: 80px; position: absolute; top: 50px; left: 100px; background: #ffffe0;}