SlideShare uma empresa Scribd logo
1 de 53
Lecture Outline

 DOM

 Accessing and Modifying DOM

 Events, revisited

 HTML-Only DOM

 Form Elements and Events
DOM

 The Document Object Model represents the browser as
  a node tree (parent, child, and sibling).

 Types of Nodes:
      Element Nodes
      Text Nodes
      Attribute Nodes
      Comment Nodes
HTML Example

 <html>
   <head><title>Sample Document</title></head>
   <body>
      <h1>An HTML Document</h1>
      <p>This is a <i>simple</i>document</p>
   </body>

 </html>
The DOM representation
    of the example
<p title="a gentle reminder">Don‟t
forget to buy this stuff.</p>,
Accessing DOM Nodes
 All nodes have
    nodeType,
    nodeName (mostly are tag names),
    nodeValue (for text nodes; the value is the actual text)

 window.document: access to the current document.
    documentElement: the root node <html>
    childNodes:
        In order to tell if a node has any children you use
         hasChildNodes(): true/false
        childNodes[] array to access child nodes of any element, has all
         array properties.
    parentNode:
        Provided to child to access its parent
childNodes Vs. children

 .children is a property of an Element. Only Elements
  have children, and these children are all of type
  Element.

 .childNodes is a property of Node. .childNodes can
  contain any node.
Accessing DOM Nodes

 window.document (Cont’d):
   attributes
      In order to tell if a node has any attributes you use
       hasAttributes()  true/false
      attributes[] array to access all attribute nodes of any element,
       has all array properties
      getAttribute(attrname)  to get a certain attribute by
       name .
      Each attribute node has nodeName and nodeValue
<html><head><title>My
page</title>
</head><body>
   <p class="opener">
        first paragraph           var bd=document.documentElement.
   </p>                                        children[1];
   <p>
                                   bd.childNodes.length =???
                                                            9
        <em>second</em>
        paragraph
                                   bd.childNodes[1].hasAttributes()
   </p>                             =??
                                      true
   <p id="closer">final</p>
   <!-- and that's about it -->
                                   bd.childNodes[1].getAttribute('class')
                                    =????
                                      “opener”
</body>
</html>
Accessing the Content
          Inside a Tag
 After reaching a desired node, you may need to get the
  text/HTML contained in the node by using the
  properties.
    innerText - textContent
    innerHTML (to change content of Element nodes only)
    nodeValue (this changes value of any node)

 It sets and gets the content of the element as text or as
  HTML.
A Shortcut to DOM
             elements
 document.getElementById(id)  returns an object
  representing element or null if not found
 document.getElementsByTagName(tag)  returns a
  collection of objects with the specified tag name or [] an
  empty array if not found
 document.getElementsByName(name)  returns a
  collection of objects with the specified name attribute or
  [] an empty array if not found
 Shortcut to body element:
    document.body
More on Attributes

 Once you retrieved an Element you can get/set its
  attributes through
      .attributes[index]
      .attributes[name]
      .getAttribute()/setAttribute
      .attributeName
        document.getElementsByTagName('p')[2].id
        document.getElementsByTagName('p')[2].className
A Shortcut to DOM
             elements
 document.getElementById(id)  returns an object
  representing element or null if not found

 document.getElementsByTagName(tag)  returns a
  collection of objects with the specified tag name or [] an
  empty array if not found

 document.getElementsByName(name)  returns a
  collection of objects with the specified name attribute or
  [] an empty array if not found
Modifying Style

 Most of the element nodes have a style property, which in
  turn has a property mapped to each CSS property.

 Example:
    var my = document.getElementById(’mydiv');
    my.style.border = "1px solid red";

 CSS properties have dashes but in JavaScript map their
  names to properties by skipping the dash and uppercase
  the next letter.
    padding-top  paddingTop, margin-left  marginLeft…..
Modifying Style (Cont‟d)

 You can change the css class using the className
  property or setAttribute() function.

 Example:
    var m=document.getElementById(„mydiv‟);
    m.className=“errorclass”;

 OR
    m.setAttribute(„class‟,‟errorname‟);
Creating New Nodes

 Create element nodes by createElement() and
  createTextNode().

 Once you have the new nodes, you add them to the
  DOM tree with appendChild().

 Example
      var myp = document.createElement('p');
      myp.innerHTML = 'yet another';
      myp.style.border = '2px dotted blue’
      document.body.appendChild(myp) //here appended to end
       of body directly
Clone Existing Node

 cloneNode()
   The method accepts a boolean parameter (true = deep
    copy with all the children, false = shallow copy, only
    this node).
   Get a reference to the element you want to clone:
      var el = document.getElementsByTagName('p')[1];
   Create a shallow clone of el and append it to the body:
      document.body.appendChild(el.cloneNode(false))
   Create a deep copy, the whole DOM subtree
      document.body.appendChild(el.cloneNode(true))
insertBefore

 insertBefore is the same as appendChild(), but accepts
  an extra parameter, specifying before which element to
  insert the new node.

 Example:
    At the end of the body:
       document.body.appendChild(document.createTextNode('boo!'));
    Add it as the first child of the body:
       document.body.insertBefore(document.createTextNode('boo!'),
        document.body.firstChild);
Removing/Replacing
             Nodes
 removeChild().

    Specify node to be removed, send it to removeChild
        var removed = document.body.removeChild(myp);
    The method returns the removed node if you want to use it
     later.

 replaceChild()
    Removes a node and puts another one in its place.
    First specify node to remove and node to add, then send them
     to function
        var replaced = document.body.replaceChild(removed, pAdded);
    It returns a reference to the node that is now out of the tree.
Question?

 How to remove all subtree of body?

        document.body.innerHTML = ’’;
Events

 Events can be attached to JavaScript code through one
  of the following ways:
    Inline HTML Attributes (already discussed)
    Element Properties
    DOM Event Listeners
Elements Properties
 assign a function to the on-event property of a DOM node
  element.
 Example:
 <div id="my-div">click</div>
 <script type="text/javascript">
       var myelement = document.getElementById('my-div');
       myelement.onclick = function()
       {
                alert('Div Clicked!');
       }
 </script>

 You can attach only one function to the event.
DOM Event Listeners

 This method allows for many functions listening to an
  event. When the event fires, all functions are executed.
 Example:
   <p id="closer">final</p>
   var mypara = document.getElementById('my-div');
   mypara.addEventListener('click', function(){alert('Boo!’)}, false);
   mypara.addEventListener('click', myHandler, false);
   Where myHandler is a name of a defined function

 You can use anonymous functions such as
  function(){alert('Boo!')} or existing functions such as
  myHandler.
DOM Event Listeners

 As events are added using listeners they can be
  removed too.

 removeEventListener()  accepts exactly the same
  parameters. mypara.removeEventListener('click',
  myHandler, false);

 You cannot remove listeners that use anonymous
  functions.

 If you remove a listener, you have to pass a pointer to
  the same function you previously attached.
Always keep in mind that
HTML is for content, JavaScript
for behavior and CSS for
formatting, and you should keep
these three SEPARATE as
much as possible.
HTML-only DOM objects

 document objects that represent a number of collections:
      document.images
      document.anchors
      document.forms
      document.links
      document.styleSheets

 Other useful properties
    document.cookie
    document.referrer
document.images

 A collection of all images images on the page

 Equivalent to
  document.getElementsByTagName(„img)
Image Objects
 Image Object represent an HTML Image

 Has its own set of Properties, Collections, Methods & Event
  handlers.

 Properties:
       name
       id
       src
       height
       width

 Image Preloading can boost performance, by creating Image objects
  and after loading start assigning them to HTML
document.anchors

 document.anchors- contains all links with a name
  attribute (<a name="..."></a>).

 Anchor Object
    The Anchor object represents an HTMLAnchor.
    Properties:
       href
       name
       target
document.forms
               Form Object
 document.forms - contains a list of <form> tags.

 Properties of Form Object
    elements[]: a collection of elements of the form
    Example:
       <input name="search" id="search" type="text” value="Enter
        email..." />
       To change the text in the field by:
             document.forms[0].elements[0].value = 'me@example.org’
       To disable the field dynamically:
             document.forms[0].elements[0].disabled = true;
    method,action
document.forms

 When forms or form elements have a name attribute, you can
  access them by name too:
    document.forms[0].elements['search']; // array notation
    document.forms[0].elements.search; // object property

 Methods of Form Object:
    reset()
    submit()

 Events of Form Object:
    Onreset
    onsubmit
Form Elements Events

 Use „this‟ keyword to refer to the current object.

 Self reference to the object is used
    document.forms[0].elements['name'].onchange=function(){al
     ert(this)} on text change will alert
Form Elements

 Common Properties    Common Methods
      name              focus()/blur()
      value
                       Common Events
      form
                         onfocus/onblur
      disabled
                         onclick/ondblclick
                         onmousedown
                         onmousemove/onmouseo
                          ve
                         onmouseout/onmouseup
Input Text/Password

 Properties:
    maxLength
    readOnly

 Methods
    select()

 Events
    onchange
Input Radio/Checkbox

 Properties:
    length
    checked
    defaultChecked

 Events
    onclick
    onchange
Input Button

 Events:
     onclick
     ondblclick
     onmousedown
     onmouseout
     onmouseover
     onmouseup
Select

 Properties                      Method (not with IE
      length                      prior 8 )
      multiple                      add()
      selectedIndex                 remove()
      options[]
                                  Events
          selected
                                     onchange
          text
          defaultSelected
Option

 Properties
    selected
    text
    defaultSelected

 Options can be added dynamically to a Select element.
    First create a new Option object.
    Set its value and text.
    Send to add method of Select Element.
Textarea

 Properties                Method:
      cols                   select()
      defaultValue
                            Events
      readOnly
                              onselect
      rows
Try Form validation
styleSheets

 document.styleSheets[]
    All the external style sheets on the page, either defined
     using the <style> or <link rel="stylesheet"> tag.
    To add or delete rules within any stylesheet on the page.
styleSheets Properties
 cssRules[]
        Returns an array containing all the CSS rules of a stylesheet. NS6+/Firefox
         only object. In IE (Win), use rules[] instead.
        cssText
              Read/write property that contains the entire contents of the stylesheet. IE
              only property. Note that Firefox support a "cssText" property on individual
              rules to return the contents of each rule.

 disabled :
        Read/write property that specifies whether a stylesheet is diabled or not.
         Default value is false.

 href
        Read/write property that specifies the URL of an external stylesheet.

 media
        Specifies the medium of the stylesheet. Default value is "screen.”
styleSheets[] Methods
 addRule(selector, declaration, [index])
       IE : adds a new rule to the stylesheet,
        "selector” ex: "p", "div b” ……etc
        "declaration” ex: "background-color: yellow; color: brown”
        "index" optional, default is -1, which adds the new rule to the
         end.
 removeRule([index]) :
    IE: removes the first rule, index (optional) to remove rule at index.
 deleteRule(index):
    Removes a rule based on its index. DOM2 NS/Firefox only
     property.
 insertRule(rule, index):
       Inserts a new rule to the stylesheet,
        "rule” ex: #myid{color: red; border: 1px solid black}
        "index", NS/Firefox only property.
document.cookie

 It is a property that contains a string, the content of the
  cookies exchanged between the server and the client.

 When the server sends a page to the browser, it may
  include the Set-Cookie HTTP header.

 When the client sends a request to the server, it sends
  the cookie information back with the Cookie header.
document.cookie

 Cookie Attributes
    name-value pair
       Each cookie has a name-value pair that contains the actual
        information.
    expires
       If not specified, the cookie is trashed when you close the
        browser. It id in UTC (Greenwich) time.
    path
       to specify directory where the cookie is active. Usually „/‟,
         the entire domain.
    domain
       Which domain the cookie should be sent to. Other domains
        cannot read them.
       Can‟t be set to a domain other than the one setting it.
document.cookie

 To set cookie, assign string with all attributes to
  document.cookie

 Example:
    var nextyear = new Date( );
     nextyear.setFullYear(nextyear.getFullYear( ) + 1);
    document.cookie = ”intake=33;track=PD; expires=" +
     nextyear.toGMTString( );
How to DELETE a cookie

 Create a cookie with expired date
document.referrer

 Returns the URI of the page that linked to this page.

 This is the same value the browser sends in the Referer
  HTTP header when requesting the page.

 There is also:
    document.location
    document.title
    document.domain
References
 DomScripting, Web Design with JavaScript and DOM, Jeremy
  Keith, 2008 .

 Object-Oriented JavaScript Create Scalable, reusable, high
  quality JavaScript applications and libraries, Stoyan Stefanov,
  2008.

 JavaScript by Example, Second Edition, Ellie Quigley, 2011

 JavaScript, the Definitive Guide, 5th edition, David Flanagan,
  2006

 http://www.quirksmode.org/js

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

php
phpphp
php
 
Database Connection
Database ConnectionDatabase Connection
Database Connection
 
VB net lab.pdf
VB net lab.pdfVB net lab.pdf
VB net lab.pdf
 
Js ppt
Js pptJs ppt
Js ppt
 
Document object model
Document object modelDocument object model
Document object model
 
Java awt
Java awtJava awt
Java awt
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
jQuery
jQueryjQuery
jQuery
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
Css selectors
Css selectorsCss selectors
Css selectors
 
Types of Selectors (HTML)
Types of Selectors (HTML)Types of Selectors (HTML)
Types of Selectors (HTML)
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Introduction to the DOM
Introduction to the DOMIntroduction to the DOM
Introduction to the DOM
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
MySQL JOINS
MySQL JOINSMySQL JOINS
MySQL JOINS
 
html-table
html-tablehtml-table
html-table
 

Semelhante a DOM and Events

12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objects
Phúc Đỗ
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance Tips
Ravi Raj
 
Week32
Week32Week32
Week32
H K
 

Semelhante a DOM and Events (20)

Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
 
Java script
Java scriptJava script
Java script
 
INTRODUCTION TO DOM AND DOM TREE
INTRODUCTION TO DOM AND DOM TREEINTRODUCTION TO DOM AND DOM TREE
INTRODUCTION TO DOM AND DOM TREE
 
Java Script and HTML.
Java Script and HTML.Java Script and HTML.
Java Script and HTML.
 
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
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objects
 
Jquery 2
Jquery 2Jquery 2
Jquery 2
 
Dom structure
Dom structure Dom structure
Dom structure
 
Automating Ievb
Automating IevbAutomating Ievb
Automating Ievb
 
13488117.ppt
13488117.ppt13488117.ppt
13488117.ppt
 
13488117.ppt
13488117.ppt13488117.ppt
13488117.ppt
 
Javascript.ppt
Javascript.pptJavascript.ppt
Javascript.ppt
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
Javascript 2
Javascript 2Javascript 2
Javascript 2
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance Tips
 
Jquery
JqueryJquery
Jquery
 
Week32
Week32Week32
Week32
 

Mais de Julie Iskander

Mais de Julie Iskander (20)

HTML 5
HTML 5HTML 5
HTML 5
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 
Design Pattern lecture 3
Design Pattern lecture 3Design Pattern lecture 3
Design Pattern lecture 3
 
Scriptaculous
ScriptaculousScriptaculous
Scriptaculous
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
Design Pattern lecture 4
Design Pattern lecture 4Design Pattern lecture 4
Design Pattern lecture 4
 
Design Pattern lecture 2
Design Pattern lecture 2Design Pattern lecture 2
Design Pattern lecture 2
 
Design Pattern lecture 1
Design Pattern lecture 1Design Pattern lecture 1
Design Pattern lecture 1
 
Ajax and ASP.NET AJAX
Ajax and ASP.NET AJAXAjax and ASP.NET AJAX
Ajax and ASP.NET AJAX
 
jQuery
jQueryjQuery
jQuery
 
ASP.NET Lecture 5
ASP.NET Lecture 5ASP.NET Lecture 5
ASP.NET Lecture 5
 
ASP.NET lecture 8
ASP.NET lecture 8ASP.NET lecture 8
ASP.NET lecture 8
 
ASP.NET Lecture 7
ASP.NET Lecture 7ASP.NET Lecture 7
ASP.NET Lecture 7
 
ASP.NET Lecture 6
ASP.NET Lecture 6ASP.NET Lecture 6
ASP.NET Lecture 6
 
ASP.NET Lecture 4
ASP.NET Lecture 4ASP.NET Lecture 4
ASP.NET Lecture 4
 
ASP.NET Lecture 3
ASP.NET Lecture 3ASP.NET Lecture 3
ASP.NET Lecture 3
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
 
ASP.NET Lecture 1
ASP.NET Lecture 1ASP.NET Lecture 1
ASP.NET Lecture 1
 
AJAX and JSON
AJAX and JSONAJAX and JSON
AJAX and JSON
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

DOM and Events

  • 1.
  • 2. Lecture Outline  DOM  Accessing and Modifying DOM  Events, revisited  HTML-Only DOM  Form Elements and Events
  • 3.
  • 4. DOM  The Document Object Model represents the browser as a node tree (parent, child, and sibling).  Types of Nodes:  Element Nodes  Text Nodes  Attribute Nodes  Comment Nodes
  • 5. HTML Example  <html>  <head><title>Sample Document</title></head>  <body>  <h1>An HTML Document</h1>  <p>This is a <i>simple</i>document</p>  </body>  </html>
  • 6. The DOM representation of the example
  • 7. <p title="a gentle reminder">Don‟t forget to buy this stuff.</p>,
  • 8. Accessing DOM Nodes  All nodes have  nodeType,  nodeName (mostly are tag names),  nodeValue (for text nodes; the value is the actual text)  window.document: access to the current document.  documentElement: the root node <html>  childNodes:  In order to tell if a node has any children you use hasChildNodes(): true/false  childNodes[] array to access child nodes of any element, has all array properties.  parentNode:  Provided to child to access its parent
  • 9. childNodes Vs. children  .children is a property of an Element. Only Elements have children, and these children are all of type Element.  .childNodes is a property of Node. .childNodes can contain any node.
  • 10. Accessing DOM Nodes  window.document (Cont’d):  attributes  In order to tell if a node has any attributes you use hasAttributes()  true/false  attributes[] array to access all attribute nodes of any element, has all array properties  getAttribute(attrname)  to get a certain attribute by name .  Each attribute node has nodeName and nodeValue
  • 11. <html><head><title>My page</title> </head><body> <p class="opener"> first paragraph var bd=document.documentElement. </p> children[1]; <p>  bd.childNodes.length =??? 9 <em>second</em> paragraph  bd.childNodes[1].hasAttributes() </p> =?? true <p id="closer">final</p> <!-- and that's about it -->  bd.childNodes[1].getAttribute('class') =???? “opener” </body> </html>
  • 12. Accessing the Content Inside a Tag  After reaching a desired node, you may need to get the text/HTML contained in the node by using the properties.  innerText - textContent  innerHTML (to change content of Element nodes only)  nodeValue (this changes value of any node)  It sets and gets the content of the element as text or as HTML.
  • 13. A Shortcut to DOM elements  document.getElementById(id)  returns an object representing element or null if not found  document.getElementsByTagName(tag)  returns a collection of objects with the specified tag name or [] an empty array if not found  document.getElementsByName(name)  returns a collection of objects with the specified name attribute or [] an empty array if not found  Shortcut to body element:  document.body
  • 14. More on Attributes  Once you retrieved an Element you can get/set its attributes through  .attributes[index]  .attributes[name]  .getAttribute()/setAttribute  .attributeName  document.getElementsByTagName('p')[2].id  document.getElementsByTagName('p')[2].className
  • 15. A Shortcut to DOM elements  document.getElementById(id)  returns an object representing element or null if not found  document.getElementsByTagName(tag)  returns a collection of objects with the specified tag name or [] an empty array if not found  document.getElementsByName(name)  returns a collection of objects with the specified name attribute or [] an empty array if not found
  • 16. Modifying Style  Most of the element nodes have a style property, which in turn has a property mapped to each CSS property.  Example:  var my = document.getElementById(’mydiv');  my.style.border = "1px solid red";  CSS properties have dashes but in JavaScript map their names to properties by skipping the dash and uppercase the next letter.  padding-top  paddingTop, margin-left  marginLeft…..
  • 17. Modifying Style (Cont‟d)  You can change the css class using the className property or setAttribute() function.  Example:  var m=document.getElementById(„mydiv‟);  m.className=“errorclass”;  OR  m.setAttribute(„class‟,‟errorname‟);
  • 18. Creating New Nodes  Create element nodes by createElement() and createTextNode().  Once you have the new nodes, you add them to the DOM tree with appendChild().  Example  var myp = document.createElement('p');  myp.innerHTML = 'yet another';  myp.style.border = '2px dotted blue’  document.body.appendChild(myp) //here appended to end of body directly
  • 19. Clone Existing Node  cloneNode()  The method accepts a boolean parameter (true = deep copy with all the children, false = shallow copy, only this node).  Get a reference to the element you want to clone:  var el = document.getElementsByTagName('p')[1];  Create a shallow clone of el and append it to the body:  document.body.appendChild(el.cloneNode(false))  Create a deep copy, the whole DOM subtree  document.body.appendChild(el.cloneNode(true))
  • 20. insertBefore  insertBefore is the same as appendChild(), but accepts an extra parameter, specifying before which element to insert the new node.  Example:  At the end of the body:  document.body.appendChild(document.createTextNode('boo!'));  Add it as the first child of the body:  document.body.insertBefore(document.createTextNode('boo!'), document.body.firstChild);
  • 21. Removing/Replacing Nodes  removeChild().  Specify node to be removed, send it to removeChild  var removed = document.body.removeChild(myp);  The method returns the removed node if you want to use it later.  replaceChild()  Removes a node and puts another one in its place.  First specify node to remove and node to add, then send them to function  var replaced = document.body.replaceChild(removed, pAdded);  It returns a reference to the node that is now out of the tree.
  • 22. Question?  How to remove all subtree of body? document.body.innerHTML = ’’;
  • 23.
  • 24. Events  Events can be attached to JavaScript code through one of the following ways:  Inline HTML Attributes (already discussed)  Element Properties  DOM Event Listeners
  • 25. Elements Properties  assign a function to the on-event property of a DOM node element.  Example:  <div id="my-div">click</div>  <script type="text/javascript"> var myelement = document.getElementById('my-div'); myelement.onclick = function() { alert('Div Clicked!'); }  </script>  You can attach only one function to the event.
  • 26. DOM Event Listeners  This method allows for many functions listening to an event. When the event fires, all functions are executed.  Example: <p id="closer">final</p> var mypara = document.getElementById('my-div'); mypara.addEventListener('click', function(){alert('Boo!’)}, false); mypara.addEventListener('click', myHandler, false); Where myHandler is a name of a defined function  You can use anonymous functions such as function(){alert('Boo!')} or existing functions such as myHandler.
  • 27. DOM Event Listeners  As events are added using listeners they can be removed too.  removeEventListener()  accepts exactly the same parameters. mypara.removeEventListener('click', myHandler, false);  You cannot remove listeners that use anonymous functions.  If you remove a listener, you have to pass a pointer to the same function you previously attached.
  • 28. Always keep in mind that HTML is for content, JavaScript for behavior and CSS for formatting, and you should keep these three SEPARATE as much as possible.
  • 29.
  • 30. HTML-only DOM objects  document objects that represent a number of collections:  document.images  document.anchors  document.forms  document.links  document.styleSheets  Other useful properties  document.cookie  document.referrer
  • 31. document.images  A collection of all images images on the page  Equivalent to document.getElementsByTagName(„img)
  • 32. Image Objects  Image Object represent an HTML Image  Has its own set of Properties, Collections, Methods & Event handlers.  Properties:  name  id  src  height  width  Image Preloading can boost performance, by creating Image objects and after loading start assigning them to HTML
  • 33. document.anchors  document.anchors- contains all links with a name attribute (<a name="..."></a>).  Anchor Object  The Anchor object represents an HTMLAnchor.  Properties:  href  name  target
  • 34. document.forms Form Object  document.forms - contains a list of <form> tags.  Properties of Form Object  elements[]: a collection of elements of the form  Example:  <input name="search" id="search" type="text” value="Enter email..." />  To change the text in the field by:  document.forms[0].elements[0].value = 'me@example.org’  To disable the field dynamically:  document.forms[0].elements[0].disabled = true;  method,action
  • 35. document.forms  When forms or form elements have a name attribute, you can access them by name too:  document.forms[0].elements['search']; // array notation  document.forms[0].elements.search; // object property  Methods of Form Object:  reset()  submit()  Events of Form Object:  Onreset  onsubmit
  • 36. Form Elements Events  Use „this‟ keyword to refer to the current object.  Self reference to the object is used  document.forms[0].elements['name'].onchange=function(){al ert(this)} on text change will alert
  • 37. Form Elements  Common Properties  Common Methods  name  focus()/blur()  value  Common Events  form  onfocus/onblur  disabled  onclick/ondblclick  onmousedown  onmousemove/onmouseo ve  onmouseout/onmouseup
  • 38. Input Text/Password  Properties:  maxLength  readOnly  Methods  select()  Events  onchange
  • 39. Input Radio/Checkbox  Properties:  length  checked  defaultChecked  Events  onclick  onchange
  • 40. Input Button  Events:  onclick  ondblclick  onmousedown  onmouseout  onmouseover  onmouseup
  • 41. Select  Properties  Method (not with IE  length prior 8 )  multiple  add()  selectedIndex  remove()  options[]  Events  selected  onchange  text  defaultSelected
  • 42. Option  Properties  selected  text  defaultSelected  Options can be added dynamically to a Select element.  First create a new Option object.  Set its value and text.  Send to add method of Select Element.
  • 43. Textarea  Properties  Method:  cols  select()  defaultValue  Events  readOnly  onselect  rows
  • 45. styleSheets  document.styleSheets[]  All the external style sheets on the page, either defined using the <style> or <link rel="stylesheet"> tag.  To add or delete rules within any stylesheet on the page.
  • 46. styleSheets Properties  cssRules[]  Returns an array containing all the CSS rules of a stylesheet. NS6+/Firefox only object. In IE (Win), use rules[] instead.  cssText  Read/write property that contains the entire contents of the stylesheet. IE only property. Note that Firefox support a "cssText" property on individual rules to return the contents of each rule.  disabled :  Read/write property that specifies whether a stylesheet is diabled or not. Default value is false.  href  Read/write property that specifies the URL of an external stylesheet.  media  Specifies the medium of the stylesheet. Default value is "screen.”
  • 47. styleSheets[] Methods  addRule(selector, declaration, [index])  IE : adds a new rule to the stylesheet,  "selector” ex: "p", "div b” ……etc  "declaration” ex: "background-color: yellow; color: brown”  "index" optional, default is -1, which adds the new rule to the end.  removeRule([index]) :  IE: removes the first rule, index (optional) to remove rule at index.  deleteRule(index):  Removes a rule based on its index. DOM2 NS/Firefox only property.  insertRule(rule, index):  Inserts a new rule to the stylesheet,  "rule” ex: #myid{color: red; border: 1px solid black}  "index", NS/Firefox only property.
  • 48. document.cookie  It is a property that contains a string, the content of the cookies exchanged between the server and the client.  When the server sends a page to the browser, it may include the Set-Cookie HTTP header.  When the client sends a request to the server, it sends the cookie information back with the Cookie header.
  • 49. document.cookie  Cookie Attributes  name-value pair  Each cookie has a name-value pair that contains the actual information.  expires  If not specified, the cookie is trashed when you close the browser. It id in UTC (Greenwich) time.  path  to specify directory where the cookie is active. Usually „/‟,  the entire domain.  domain  Which domain the cookie should be sent to. Other domains cannot read them.  Can‟t be set to a domain other than the one setting it.
  • 50. document.cookie  To set cookie, assign string with all attributes to document.cookie  Example:  var nextyear = new Date( ); nextyear.setFullYear(nextyear.getFullYear( ) + 1);  document.cookie = ”intake=33;track=PD; expires=" + nextyear.toGMTString( );
  • 51. How to DELETE a cookie  Create a cookie with expired date
  • 52. document.referrer  Returns the URI of the page that linked to this page.  This is the same value the browser sends in the Referer HTTP header when requesting the page.  There is also:  document.location  document.title  document.domain
  • 53. References  DomScripting, Web Design with JavaScript and DOM, Jeremy Keith, 2008 .  Object-Oriented JavaScript Create Scalable, reusable, high quality JavaScript applications and libraries, Stoyan Stefanov, 2008.  JavaScript by Example, Second Edition, Ellie Quigley, 2011  JavaScript, the Definitive Guide, 5th edition, David Flanagan, 2006  http://www.quirksmode.org/js

Notas do Editor

  1. document.documentElement.nodeType 1document.documentElement.nodeName &quot;HTML&quot;document.documentElement.tagName &quot;HTML”The HTML element has two children—the head and the body elements. You can access them using the childNodes array-like collection.document.documentElement.childNodes[1].parentNode
  2. var bd= document.documentElement;bd.childNodes[1].attributes[0].nodeNamebd.childNodes[1].attributes[0].nodeValuebd.childNodes[1].attributes[&apos;class&apos;].nodeValuebd.childNodes[1].getAttribute(&apos;class’)
  3. var bd= document.documentElement;bd.childNodes[1].attributes[0].nodeNamebd.childNodes[1].attributes[0].nodeValuebd.childNodes[1].attributes[&apos;class&apos;].nodeValuebd.childNodes[1].getAttribute(&apos;class’)
  4. currentStyleruntimeStyle objects to retrieve style works with IE only
  5. When may this be undesirable? When the DOM nodes has event handlers attached to it.
  6. N.B. This way is actually better because it helps you keep your &lt;div&gt; clean of any JavaScript code.
  7. Style property accesses only inline style of element.The DOM provides a way to access an element’s style values: the getComputedStyle() function. IE does also: the element.currentStyle property.
  8. cookie is a string property that allows you to read, create, modify, and delete the cookie or cookies that apply to the current web page.
  9. cookie is a string property that allows you to read, create, modify, and delete the cookie or cookies that apply to the current web page.
  10. the name/value pair you stored is included in the list of cookies for the document. Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape( ) function to encode the value before storing it in the cookie. If you do this, you&apos;ll have to use the corresponding unescape( ) function when you read the cookie value.