JavaScript DOM Manipulations

Ynon Perek
Ynon PerekTeaching online courses at ToCode.co.il em ToCode.co.il
JavaScript
  DOM Manipulations and Events

  Slides By: Ynon Perek

  Fine me at: http://ynonperek.com


Friday, April 12, 13
The Task
    Read text                                                                   Make web
   <BODY BGCOLOR='#FFFFFF' style="overflow:hidden;"
   LEFTMARGIN=0 MARGINWIDTH=0 TOPMARGIN=0
   MARGINHEIGHT=0 CLASS="text" onload="DisplayAD();"
   onresize="if(typeof DZresize == 'function'){DZresize();};if(typeof
   dcOnResize == 'function'){dcOnResize();};if(typeof
   disYnetAdColOnResize == 'function'){disYnetAdColOnResize();};"
   lang=he><div id='divRedAlert' style='display:none;'></div><iframe
   id=frmRedAlert name=frmRedAlert frameborder=0 width=0 height=0
   MARGINHEIGHT=0 MARGINWIDTH=0 src='/Ext/App/RedAlert/
   CdaRedAlert_iframe/0,12639,84-234-208-20,00.html'></iframe><div
   id='ads.ozen' style='position:absolute;z-index:2;left:0;top:0;'></div><div
   id='ads.elvisR.1' style='position:absolute;z-index:2;right:0;top:0;'></
   div><div id=mainCont style="overflow:hidden; width:100%; height:100%;"
   align=center ><div id='mainSpacer' style='overflow:auto;height:
   100%'><script>
   <style>A.brightgrey:link{color:#7d7f7e}
   A.brightgrey:visited{color:#7d7f7e}A.brightgrey:active{color:#7d7f7e}
   A.brightgrey:hover{color:#f00}A.upnvl{color:#7d7f80}
   A.upnvl:visited{color:#7d7f80}A.upnvl:hover{color:#f00}
   A.btnvl{color:#7f90b0}A.btnvl:visited{color:#7f90b0}
   A.btnvl:hover{color:#f00}</style><table id=tbl_logos cellspacing=0 cetd
   width='46' align='left' style='line-height:12px;'><a href='http://
   www.ynetnews.com/home/0,7340,L-3083,00.html' class='text11
   btnvl'>English</a></td></tr></table></div></td><td width=11>&nbsp;</
   td><td width=2 bgcolor=black></td><td width=11>&nbsp;</td><td
   width=132 valign=top style='direction: rtl;' class='ghci3' ><div
   id=divMainLogo style='margin-top:1px;'></div></td><td width=11><div
   style='width:11px;'></div></td><TD WIDTH=194 align=right dir=rtl
   VALIGN=top class='ghciTopStoryMain1' ><div dir=ltr style='height:
   38px;overflow:hidden;'><IMG SRC='/Common/Files/Images/Date/12.gif'
   alt="12/04/2013 11:20"><IMG SRC='/Common/Files/Images/D...




Friday, April 12, 13
How Browsers Render


                       • Each browser has a Rendering Engine
                       • Rendering Engine takes an HTML text
                         and produces a DOM tree




Friday, April 12, 13
Rendering Engines
     Engine                Browser           Developer


     Blink                 Google Chrome     Google


     Gecko                 Mozilla Firefox   Mozilla


     Trident               IE                Microsoft

                                             Apple, KDE, Nokia,
     Webkit                Apple Safari
                                             Others



Friday, April 12, 13
How Browsers Work
                        Parse HTML to make DOM Tree


                         Build Render Tree from CSS


                              Layout Elements


                                   Paint

Friday, April 12, 13
What’s a DOM Tree

    <html>
    <body>
      <p>
                       Hello World
      </p>
      <div>
       <img src="example.png"/>
      </div>
    </body>
    </html>




Friday, April 12, 13
Rendering DOM Tree




Friday, April 12, 13
Rendering DOM Tree


                       • A Render tree is derived from DOM
                         tree
                       • It’s not a 1-1 relation




Friday, April 12, 13
Browser Flow

                       • Read page as text
                       • Create DOM tree
                       • Create Render tree
                       • Paint



Friday, April 12, 13
Enter JavaScript

                       • Read page as text
                       • Create DOM tree        JavaScript
                                              Manipulates the
                       • Create Render tree
                                                   data
                       • Paint



Friday, April 12, 13
Enter JavaScript

                       • JavaScript alters page load

                       • JavaScript alters DOM Tree
                       • JavaScript creates interactivity through
                         events handling




Friday, April 12, 13
JavaScript and DOM
   <!DOCTYPE html>
   <html>
   <head>
     <title></title>
   </head>
   <body>                  A <script> element is
     <script>
       var x = 5;          executed in place
       var y = 3;
       console.log('Hello From JS');
     </script>
     <p>This is just some text</p>
   </body>
   </html>




Friday, April 12, 13
Q&A
         Browser Page Rendering




Friday, April 12, 13
Interactive Apps


                       • Browser is a programming platform
                       • A web application is interactive




Friday, April 12, 13
Interactivity


                       • Browser itself is interactive
                       • In addition: A web page is interactive
                       • Demo




Friday, April 12, 13
Browser Events Loop

                                  Event Queue

                                                click




Friday, April 12, 13
Event Loop

                        Wait for Events




                        Handle Events



Friday, April 12, 13
Event Loop

                        Wait for Events




                        Handle Events



Friday, April 12, 13
Event Loop

                        Wait for Events




                        Handle Events



Friday, April 12, 13
Event Handling

                       DOM Node

                          +           Event Handler (code)

                         Event



Friday, April 12, 13
Code Outline


                       • From HTML:
                        • <a on...=”handleEvent()”>




Friday, April 12, 13
Code Outline
                       • But this can get messy
                         <a href="#" onclick="doclick"
                             onblur="doblur"
                             onchange="dochange"
                             ondblclick="dodblclick"
                             onmousemove="domove"
                             onmouseover="doover">
                         Too many events</a>



Friday, April 12, 13
Code Outline


                       • From JS
                        • Get a DOM node
                        • Bind event to code




Friday, April 12, 13
Getting DOM Nodes


                       • getElementById(...)
                       • getElementsByTagName(...)
                       • querySelector(...) - IE8 and up




Friday, April 12, 13
Browser Events

                       • All browsers use:
                         node.onevent = ...
                       • IE uses:
                         node.attachEvent(...)
                       • Other browsers use
                         node.addEventListener(...)


Friday, April 12, 13
Demo: Events


                       • Write a simple page that shows alert as
                         a response to click event
                       • Modify to change text of element




Friday, April 12, 13
Using the Event Object
                       • Event object includes info on the event
                       • Print it to console for inspection

                <button>Click Me</button>
           
                <script>
                  var btn = document.getElementsByTagName('button')[0];
                  btn.onclick = function(e) {
                    if ( ! e ) e = window.event;
           
                    console.dir( e );
                  };
                </script>


Friday, April 12, 13
Capturing vs. Bubbling

                      | |                                   / 
       ---------------| |-----------------   ---------------| |-----------------
       | element1     | |                |   | element1     | |                |
       |   -----------| |-----------     |   |   -----------| |-----------     |
       |   |element2  /           |     |   |   |element2 | |           |     |
       |   -------------------------     |   |   -------------------------     |
       |        Event CAPTURING          |   |        Event BUBBLING           |
       -----------------------------------   -----------------------------------




Friday, April 12, 13
Capturing vs. Bubbling

                      | |                                   / 
       ---------------| |-----------------   ---------------| |-----------------
       | element1     | |                |   | element1     | |                |
       |   -----------| |-----------     |   |   -----------| |-----------     |
       |   |element2  /           |     |   |   |element2 | |           |     |
       |   -------------------------     |   |   -------------------------     |
       |        Event CAPTURING          |   |        Event BUBBLING           |
       -----------------------------------   -----------------------------------


         Netscape                             Microsoft




Friday, April 12, 13
Capturing vs. Bubbling

                                        | | / 
                       -----------------| |--| |-----------------
                       | element1       | | | |                 |
                       |   -------------| |--| |-----------     |
                       |   |element2     / | |           |     |
                       |   --------------------------------     |
                       |        W3C event model                 |
                       ------------------------------------------




Friday, April 12, 13
Capturing vs. Bubbling

                       • node.addEventListener takes a third
                         parameter
                       • true means capturing
                       • false means bubbling
                       • defaults to false



Friday, April 12, 13
Demo


                       • Capture all click events using
                         document.onclick = ...




Friday, April 12, 13
Usages


                       • Default event handlers
                       • Dynamic event handlers




Friday, April 12, 13
Double Handlers

                                  element1.onclick =
                       Element2   doSomething;
                       Element1   element2.onclick =
                                  doSomething;




Friday, April 12, 13
Double Handlers
                                  function   doSomething(e) {
                                        if   ( ! e ) e = window.event;
                       Element2    
                                        //   this refers to
                       Element1         //   the current element

                                        // for inner event:
                                        // this = element2

                                        // for outer event:
                                        // this = element1
                                  }




Friday, April 12, 13
Event Types
             Interface Events            Mouse Events       Form Events



                  load, unload            click, dblclick     submit


                                      mousedown, mouseup,
                  resize, scroll,                              reset
                                          mousemove


                       focus, blur    mouseover, mouseout


Friday, April 12, 13
Default Action

                       • Some events also have a “default”
                         action
                       • For example: A link will take you to
                         another page by default




Friday, April 12, 13
Default Action


                       • Possible to prevent
                       • return false from handler
                       • Demo




Friday, April 12, 13
Q&A
         Handling Events




Friday, April 12, 13
Events Lab

                       • Implement 5 duplicated input boxes
                       • Each input box should have the same
                         text
                       • Change one -> all change automatically




Friday, April 12, 13
Events Lab




Friday, April 12, 13
Altering Page Load


                       • Change Document
                       • Change DOM Tree
                       • Change Render Tree




Friday, April 12, 13
Change Document


                       • (Don’t) use document.write to change
                         the document as it’s being loaded
                       • Considered bad practice




Friday, April 12, 13
Change Document
    <!DOCTYPE html>
    <html>
    <head>
      <title></title>
    </head>
    <body>
      <script>
        document.write('<h1>Hello World</h1>');
      </script>
      <p>This is just some text</p>
    </body>
    </html>




Friday, April 12, 13
Change Document
      1. Browser starts to
      create DOM tree

                                 body


                                2. Finds a script tag.
                       script   Stops to execute


Friday, April 12, 13
Change Document

                                body


                                       3. script added <h1>
                       script    h1    element to document




Friday, April 12, 13
Change Document

                                body



                       script     h1      p


                4. browser can continue
                to create the <p>

Friday, April 12, 13
Avoiding document.write


                       • Can insert invalid content
                       • Clobbers DOM if called after reading
                         the document




Friday, April 12, 13
Friendlier Ways


                       • Get a DOM node
                       • Change it using DOM API




Friday, April 12, 13
Finding
         DOM
         Nodes


Friday, April 12, 13
DOM Traversal
  <body>                                    body
    <div>
      <h1>Header</h1>
      <p>
        <img src="..." />       #text       #div       #text
        Paragraph text
        <a
  href="#">google</a>       #text   #text    #h1   #text       #p
      </p>
    </div>
  </body>




Friday, April 12, 13
DOM Traversal
                       • n.childNodes[]
                       • n.firstChild
                       • n.lastChild
                       • n.nextSibling
                       • n.parentNode
                       • n.previousSibling


Friday, April 12, 13
The (Past) Future


                       • document.querySelector takes any CSS
                         selector and fetches DOM element
                       • Supported in IE8 and later




Friday, April 12, 13
DOM API

                       • Allows
                        • Getting info on elements
                        • Changing element attributes
                        • Creating new elements
                        • Setting elements style


Friday, April 12, 13
DOM API
                       • Use x.nodeName to get the tag name

                       if ( this.nodeName === 'INPUT' ){
                         // handle input element
                       }




Friday, April 12, 13
DOM API

                       • Use x.nodeValue to get/set the node
                         value

              a.firstChild.nodeValue = 'Go to google';




Friday, April 12, 13
DOM API
                       • Use getAttribute / setAttribute to
                         change element attributes


           a.setAttribute('href',
                          'http://www.google.com');




Friday, April 12, 13
Creating New Elements
                       • Create elements and text nodes using
                         document
                       • Later you can add them to the DOM

                        document.createElement('P');

                        document.createTextNode('Hello
                        World');



Friday, April 12, 13
Creating New Elements
                       • Insert new nodes by manipulating
                         existing
                        // append y to x
                        x.appendChild(y)
                         
                        // insert y to x before z
                        x.insertBefore(y,z)
                         
                        // remove y from x
                        x.removeChild(y)
                         
                        // replace y with z
                        x.replaceChild(y,z)


Friday, April 12, 13
Change Style
                       • Use .style property to set an element
                         style
                       • Note style keys are almost like CSS
                         property names

                        p.style.backgroundColor = 'blue';




Friday, April 12, 13
Q&A
         Handling Events




Friday, April 12, 13
DOM Lab
                       • Given the HTML at:
                         http://jsbin.com/ecitag/1/edit
                       • Use JavaScript to:
                        • write your name in the first <li> item
                          of the second list
                        • Change the H3 to H4
                        • Set all links to point to google.com

Friday, April 12, 13
DOM Lab


                       • Create a Money Converter calculator
                       • Support 3 currencies




Friday, April 12, 13
1 de 63

Recomendados

JavaScript & Dom Manipulation por
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
7.9K visualizações24 slides
Javascript and DOM por
Javascript and DOMJavascript and DOM
Javascript and DOMBrian Moschel
3.4K visualizações14 slides
JavaScript and BOM events por
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM eventsJussi Pohjolainen
2.6K visualizações19 slides
Javascript, DOM, browsers and frameworks basics por
Javascript, DOM, browsers and frameworks basicsJavascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsNet7
2.3K visualizações59 slides
Backbone por
BackboneBackbone
BackboneYnon Perek
2K visualizações104 slides
Why and How to Use Virtual DOM por
Why and How to Use Virtual DOMWhy and How to Use Virtual DOM
Why and How to Use Virtual DOMDaiwei Lu
1.3K visualizações38 slides

Mais conteúdo relacionado

Mais procurados

Web Performance Tips por
Web Performance TipsWeb Performance Tips
Web Performance TipsRavi Raj
639 visualizações23 slides
Javascript inside Browser (DOM) por
Javascript inside Browser (DOM)Javascript inside Browser (DOM)
Javascript inside Browser (DOM)Vlad Mysla
2.4K visualizações42 slides
Scripting The Dom por
Scripting The DomScripting The Dom
Scripting The DomAra Pehlivanian
1.3K visualizações53 slides
Angular - Chapter 4 - Data and Event Handling por
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
423 visualizações37 slides
Javascript: Ajax & DOM Manipulation v1.2 por
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2borkweb
2.3K visualizações31 slides
jQuery -Chapter 2 - Selectors and Events por
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events WebStackAcademy
210 visualizações11 slides

Mais procurados(20)

Web Performance Tips por Ravi Raj
Web Performance TipsWeb Performance Tips
Web Performance Tips
Ravi Raj639 visualizações
Javascript inside Browser (DOM) por Vlad Mysla
Javascript inside Browser (DOM)Javascript inside Browser (DOM)
Javascript inside Browser (DOM)
Vlad Mysla2.4K visualizações
Scripting The Dom por Ara Pehlivanian
Scripting The DomScripting The Dom
Scripting The Dom
Ara Pehlivanian1.3K visualizações
Angular - Chapter 4 - Data and Event Handling por WebStackAcademy
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy423 visualizações
Javascript: Ajax & DOM Manipulation v1.2 por borkweb
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
borkweb2.3K visualizações
jQuery -Chapter 2 - Selectors and Events por WebStackAcademy
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
WebStackAcademy210 visualizações
Frontend Engineer Toolbox por Ynon Perek
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer Toolbox
Ynon Perek3.3K visualizações
jQuery - Chapter 1 - Introduction por WebStackAcademy
 jQuery - Chapter 1 - Introduction jQuery - Chapter 1 - Introduction
jQuery - Chapter 1 - Introduction
WebStackAcademy682 visualizações
KMUTNB - Internet Programming 4/7 por phuphax
KMUTNB - Internet Programming 4/7KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7
phuphax787 visualizações
Java script por Sukrit Gupta
Java scriptJava script
Java script
Sukrit Gupta853 visualizações
lect9 por tutorialsruby
lect9lect9
lect9
tutorialsruby709 visualizações
AJAX Workshop Notes por Pamela Fox
AJAX Workshop NotesAJAX Workshop Notes
AJAX Workshop Notes
Pamela Fox997 visualizações
jQuery introduction por Tomi Juhola
jQuery introductionjQuery introduction
jQuery introduction
Tomi Juhola32.3K visualizações
Web Components por Nikolaus Graf
Web ComponentsWeb Components
Web Components
Nikolaus Graf2.7K visualizações
jQuery - Chapter 3 - Effects por WebStackAcademy
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
WebStackAcademy341 visualizações
Knockout.js por Vivek Rajan
Knockout.jsKnockout.js
Knockout.js
Vivek Rajan11.7K visualizações
Introduction to java_script por Basavaraj Hampali
Introduction to java_scriptIntroduction to java_script
Introduction to java_script
Basavaraj Hampali286 visualizações
Angular - Chapter 7 - HTTP Services por WebStackAcademy
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
WebStackAcademy648 visualizações
Introduction to Prototype JS Framework por Mohd Imran
Introduction to Prototype JS FrameworkIntroduction to Prototype JS Framework
Introduction to Prototype JS Framework
Mohd Imran3.4K visualizações
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology por Ayes Chinmay
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web TechnologyInternet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Ayes Chinmay153 visualizações

Destaque

Angularjs Basics por
Angularjs BasicsAngularjs Basics
Angularjs BasicsAnuradha Bandara
1.4K visualizações35 slides
Scalable JavaScript por
Scalable JavaScriptScalable JavaScript
Scalable JavaScriptYnon Perek
2.9K visualizações83 slides
Dom selecting & jQuery por
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQueryKim Hunmin
2.8K visualizações66 slides
03 Advanced JavaScript por
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScriptYnon Perek
2.5K visualizações68 slides
02 JavaScript Syntax por
02 JavaScript Syntax02 JavaScript Syntax
02 JavaScript SyntaxYnon Perek
3.9K visualizações76 slides
Introduction to the DOM por
Introduction to the DOMIntroduction to the DOM
Introduction to the DOMtharaa abu ashour
626 visualizações14 slides

Destaque(20)

Angularjs Basics por Anuradha Bandara
Angularjs BasicsAngularjs Basics
Angularjs Basics
Anuradha Bandara1.4K visualizações
Scalable JavaScript por Ynon Perek
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
Ynon Perek2.9K visualizações
Dom selecting & jQuery por Kim Hunmin
Dom selecting & jQueryDom selecting & jQuery
Dom selecting & jQuery
Kim Hunmin2.8K visualizações
03 Advanced JavaScript por Ynon Perek
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScript
Ynon Perek2.5K visualizações
02 JavaScript Syntax por Ynon Perek
02 JavaScript Syntax02 JavaScript Syntax
02 JavaScript Syntax
Ynon Perek3.9K visualizações
Introduction to the DOM por tharaa abu ashour
Introduction to the DOMIntroduction to the DOM
Introduction to the DOM
tharaa abu ashour626 visualizações
DOM Features You Didn’t Know Existed por FITC
DOM Features You Didn’t Know ExistedDOM Features You Didn’t Know Existed
DOM Features You Didn’t Know Existed
FITC658 visualizações
Working with Arrays in JavaScript por Florence Davis
Working with Arrays in JavaScriptWorking with Arrays in JavaScript
Working with Arrays in JavaScript
Florence Davis546 visualizações
Javascript basics por Solv AS
Javascript basicsJavascript basics
Javascript basics
Solv AS886 visualizações
Intro to SVGs por Ynon Perek
Intro to SVGsIntro to SVGs
Intro to SVGs
Ynon Perek1.5K visualizações
Javascript - Array - Writing por Samuel Santos
Javascript - Array - WritingJavascript - Array - Writing
Javascript - Array - Writing
Samuel Santos610 visualizações
MEAN Stack NYC Meetup 20150717: TDD Your AngularJS + Ionic Directives With jQ... por Valeri Karpov
MEAN Stack NYC Meetup 20150717: TDD Your AngularJS + Ionic Directives With jQ...MEAN Stack NYC Meetup 20150717: TDD Your AngularJS + Ionic Directives With jQ...
MEAN Stack NYC Meetup 20150717: TDD Your AngularJS + Ionic Directives With jQ...
Valeri Karpov985 visualizações
Css2 por Ynon Perek
Css2Css2
Css2
Ynon Perek1.8K visualizações
Next Generation Web Attacks – HTML 5, DOM(L3) and XHR(L2) por Shreeraj Shah
Next Generation Web Attacks – HTML 5, DOM(L3) and XHR(L2)Next Generation Web Attacks – HTML 5, DOM(L3) and XHR(L2)
Next Generation Web Attacks – HTML 5, DOM(L3) and XHR(L2)
Shreeraj Shah9K visualizações
AngularJS for designers and developers por Kai Koenig
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
Kai Koenig10.2K visualizações
Html5 apis por Ynon Perek
Html5 apisHtml5 apis
Html5 apis
Ynon Perek1.9K visualizações
Arrays por fahadshakeel
ArraysArrays
Arrays
fahadshakeel2.6K visualizações
Dom API In Java Script por Rajat Pandit
Dom API In Java ScriptDom API In Java Script
Dom API In Java Script
Rajat Pandit2.1K visualizações
Writing Reusable Web Components with jQuery and jQuery UI por Ynon Perek
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UI
Ynon Perek20.2K visualizações
Performance por Ynon Perek
PerformancePerformance
Performance
Ynon Perek1.5K visualizações

Similar a JavaScript DOM Manipulations

Fork cli tool por
Fork cli toolFork cli tool
Fork cli tooljelmersnoeck
382 visualizações15 slides
Building Your First Store App with XAML and C# por
Building Your First Store App with XAML and C#Building Your First Store App with XAML and C#
Building Your First Store App with XAML and C#Tamir Dresher
1.7K visualizações46 slides
Fast mobile web apps por
Fast mobile web appsFast mobile web apps
Fast mobile web appsIvano Malavolta
2.4K visualizações50 slides
Bundling Client Side Assets por
Bundling Client Side AssetsBundling Client Side Assets
Bundling Client Side AssetsTimothy Oxley
1K visualizações68 slides
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA por
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPAIntegrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPACheng Ta Yeh
12.1K visualizações69 slides
Speeding up mobile web apps por
Speeding up mobile web appsSpeeding up mobile web apps
Speeding up mobile web appsIvano Malavolta
783 visualizações46 slides

Similar a JavaScript DOM Manipulations(20)

Fork cli tool por jelmersnoeck
Fork cli toolFork cli tool
Fork cli tool
jelmersnoeck382 visualizações
Building Your First Store App with XAML and C# por Tamir Dresher
Building Your First Store App with XAML and C#Building Your First Store App with XAML and C#
Building Your First Store App with XAML and C#
Tamir Dresher1.7K visualizações
Fast mobile web apps por Ivano Malavolta
Fast mobile web appsFast mobile web apps
Fast mobile web apps
Ivano Malavolta2.4K visualizações
Bundling Client Side Assets por Timothy Oxley
Bundling Client Side AssetsBundling Client Side Assets
Bundling Client Side Assets
Timothy Oxley1K visualizações
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA por Cheng Ta Yeh
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPAIntegrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Cheng Ta Yeh12.1K visualizações
Speeding up mobile web apps por Ivano Malavolta
Speeding up mobile web appsSpeeding up mobile web apps
Speeding up mobile web apps
Ivano Malavolta783 visualizações
component: ruby gems for the browser por Timothy Oxley
component: ruby gems for the browsercomponent: ruby gems for the browser
component: ruby gems for the browser
Timothy Oxley1.4K visualizações
MongoTalk/Voyage por ESUG
MongoTalk/VoyageMongoTalk/Voyage
MongoTalk/Voyage
ESUG1.8K visualizações
Building with JavaScript - write less by using the right tools por Christian Heilmann
Building with JavaScript -  write less by using the right toolsBuilding with JavaScript -  write less by using the right tools
Building with JavaScript - write less by using the right tools
Christian Heilmann1.1K visualizações
Custom Android Code Templates por murphonic
Custom Android Code TemplatesCustom Android Code Templates
Custom Android Code Templates
murphonic15.5K visualizações
Fast Cordova applications por Ivano Malavolta
Fast Cordova applicationsFast Cordova applications
Fast Cordova applications
Ivano Malavolta20.3K visualizações
XPages Blast - Lotusphere 2013 por Tim Clark
XPages Blast - Lotusphere 2013XPages Blast - Lotusphere 2013
XPages Blast - Lotusphere 2013
Tim Clark4.6K visualizações
Writing JavaScript that doesn't suck por Ross Bruniges
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
Ross Bruniges3.1K visualizações
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries por Simon Willison
Jazz up your JavaScript: Unobtrusive scripting with JavaScript librariesJazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
Simon Willison48.2K visualizações
XPages Blast - Lotusphere 2012 por Tim Clark
XPages Blast - Lotusphere 2012XPages Blast - Lotusphere 2012
XPages Blast - Lotusphere 2012
Tim Clark11.2K visualizações
Tek 2013 - Building Web Apps from a New Angle with AngularJS por Pablo Godel
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Pablo Godel13.5K visualizações
Augmented Reality with JavaScript and Appcelerator Titanium por Jeff Bonnes
Augmented Reality with JavaScript and Appcelerator TitaniumAugmented Reality with JavaScript and Appcelerator Titanium
Augmented Reality with JavaScript and Appcelerator Titanium
Jeff Bonnes8.6K visualizações
Performance & Responsive Web Design por Zach Leatherman
Performance & Responsive Web DesignPerformance & Responsive Web Design
Performance & Responsive Web Design
Zach Leatherman1K visualizações
Document Object Model por chomas kandar
Document Object ModelDocument Object Model
Document Object Model
chomas kandar3.4K visualizações
Document Object Model por chomas kandar
Document Object ModelDocument Object Model
Document Object Model
chomas kandar14.3K visualizações

Mais de Ynon Perek

Regexp por
RegexpRegexp
RegexpYnon Perek
1.7K visualizações30 slides
Html5 intro por
Html5 introHtml5 intro
Html5 introYnon Perek
5.2K visualizações9 slides
09 performance por
09 performance09 performance
09 performanceYnon Perek
578 visualizações8 slides
Mobile Web Intro por
Mobile Web IntroMobile Web Intro
Mobile Web IntroYnon Perek
1.3K visualizações8 slides
Qt multi threads por
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
13.9K visualizações56 slides
Vimperl por
VimperlVimperl
VimperlYnon Perek
853 visualizações25 slides

Mais de Ynon Perek(20)

Regexp por Ynon Perek
RegexpRegexp
Regexp
Ynon Perek1.7K visualizações
Html5 intro por Ynon Perek
Html5 introHtml5 intro
Html5 intro
Ynon Perek5.2K visualizações
09 performance por Ynon Perek
09 performance09 performance
09 performance
Ynon Perek578 visualizações
Mobile Web Intro por Ynon Perek
Mobile Web IntroMobile Web Intro
Mobile Web Intro
Ynon Perek1.3K visualizações
Qt multi threads por Ynon Perek
Qt multi threadsQt multi threads
Qt multi threads
Ynon Perek13.9K visualizações
Vimperl por Ynon Perek
VimperlVimperl
Vimperl
Ynon Perek853 visualizações
Syllabus por Ynon Perek
SyllabusSyllabus
Syllabus
Ynon Perek567 visualizações
Mobile Devices por Ynon Perek
Mobile DevicesMobile Devices
Mobile Devices
Ynon Perek759 visualizações
Network por Ynon Perek
NetworkNetwork
Network
Ynon Perek1.3K visualizações
Architecture app por Ynon Perek
Architecture appArchitecture app
Architecture app
Ynon Perek2.1K visualizações
Cryptography por Ynon Perek
CryptographyCryptography
Cryptography
Ynon Perek2.9K visualizações
Unit Testing JavaScript Applications por Ynon Perek
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek2.4K visualizações
How to write easy-to-test JavaScript por Ynon Perek
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
Ynon Perek1.3K visualizações
Introduction to Selenium and Ruby por Ynon Perek
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
Ynon Perek17.1K visualizações
Introduction To Web Application Testing por Ynon Perek
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application Testing
Ynon Perek3.3K visualizações
Accessibility por Ynon Perek
AccessibilityAccessibility
Accessibility
Ynon Perek579 visualizações
Angularjs por Ynon Perek
AngularjsAngularjs
Angularjs
Ynon Perek3.2K visualizações
Js memory por Ynon Perek
Js memoryJs memory
Js memory
Ynon Perek2.6K visualizações
Qt Design Patterns por Ynon Perek
Qt Design PatternsQt Design Patterns
Qt Design Patterns
Ynon Perek8.4K visualizações
Web Application Security por Ynon Perek
Web Application SecurityWeb Application Security
Web Application Security
Ynon Perek1.9K visualizações

Último

Microchip: CXL Use Cases and Enabling Ecosystem por
Microchip: CXL Use Cases and Enabling EcosystemMicrochip: CXL Use Cases and Enabling Ecosystem
Microchip: CXL Use Cases and Enabling EcosystemCXL Forum
129 visualizações12 slides
Astera Labs: Intelligent Connectivity for Cloud and AI Infrastructure por
Astera Labs:  Intelligent Connectivity for Cloud and AI InfrastructureAstera Labs:  Intelligent Connectivity for Cloud and AI Infrastructure
Astera Labs: Intelligent Connectivity for Cloud and AI InfrastructureCXL Forum
125 visualizações16 slides
TE Connectivity: Card Edge Interconnects por
TE Connectivity: Card Edge InterconnectsTE Connectivity: Card Edge Interconnects
TE Connectivity: Card Edge InterconnectsCXL Forum
96 visualizações12 slides
Throughput por
ThroughputThroughput
ThroughputMoisés Armani Ramírez
32 visualizações11 slides
Future of Learning - Khoong Chan Meng por
Future of Learning - Khoong Chan MengFuture of Learning - Khoong Chan Meng
Future of Learning - Khoong Chan MengNUS-ISS
31 visualizações7 slides
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi por
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi
"AI Startup Growth from Idea to 1M ARR", Oleksandr UspenskyiFwdays
26 visualizações9 slides

Último(20)

Microchip: CXL Use Cases and Enabling Ecosystem por CXL Forum
Microchip: CXL Use Cases and Enabling EcosystemMicrochip: CXL Use Cases and Enabling Ecosystem
Microchip: CXL Use Cases and Enabling Ecosystem
CXL Forum129 visualizações
Astera Labs: Intelligent Connectivity for Cloud and AI Infrastructure por CXL Forum
Astera Labs:  Intelligent Connectivity for Cloud and AI InfrastructureAstera Labs:  Intelligent Connectivity for Cloud and AI Infrastructure
Astera Labs: Intelligent Connectivity for Cloud and AI Infrastructure
CXL Forum125 visualizações
TE Connectivity: Card Edge Interconnects por CXL Forum
TE Connectivity: Card Edge InterconnectsTE Connectivity: Card Edge Interconnects
TE Connectivity: Card Edge Interconnects
CXL Forum96 visualizações
Future of Learning - Khoong Chan Meng por NUS-ISS
Future of Learning - Khoong Chan MengFuture of Learning - Khoong Chan Meng
Future of Learning - Khoong Chan Meng
NUS-ISS31 visualizações
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi por Fwdays
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi
Fwdays26 visualizações
.conf Go 2023 - Data analysis as a routine por Splunk
.conf Go 2023 - Data analysis as a routine.conf Go 2023 - Data analysis as a routine
.conf Go 2023 - Data analysis as a routine
Splunk90 visualizações
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV por Splunk
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
Splunk86 visualizações
Micron CXL product and architecture update por CXL Forum
Micron CXL product and architecture updateMicron CXL product and architecture update
Micron CXL product and architecture update
CXL Forum27 visualizações
The Importance of Cybersecurity for Digital Transformation por NUS-ISS
The Importance of Cybersecurity for Digital TransformationThe Importance of Cybersecurity for Digital Transformation
The Importance of Cybersecurity for Digital Transformation
NUS-ISS25 visualizações
Understanding GenAI/LLM and What is Google Offering - Felix Goh por NUS-ISS
Understanding GenAI/LLM and What is Google Offering - Felix GohUnderstanding GenAI/LLM and What is Google Offering - Felix Goh
Understanding GenAI/LLM and What is Google Offering - Felix Goh
NUS-ISS39 visualizações
Photowave Presentation Slides - 11.8.23.pptx por CXL Forum
Photowave Presentation Slides - 11.8.23.pptxPhotowave Presentation Slides - 11.8.23.pptx
Photowave Presentation Slides - 11.8.23.pptx
CXL Forum126 visualizações
Five Things You SHOULD Know About Postman por Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman25 visualizações
"Thriving Culture in a Product Company — Practical Story", Volodymyr Tsukur por Fwdays
"Thriving Culture in a Product Company — Practical Story", Volodymyr Tsukur"Thriving Culture in a Product Company — Practical Story", Volodymyr Tsukur
"Thriving Culture in a Product Company — Practical Story", Volodymyr Tsukur
Fwdays40 visualizações
Web Dev - 1 PPT.pdf por gdsczhcet
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet52 visualizações
JCon Live 2023 - Lice coding some integration problems por Bernd Ruecker
JCon Live 2023 - Lice coding some integration problemsJCon Live 2023 - Lice coding some integration problems
JCon Live 2023 - Lice coding some integration problems
Bernd Ruecker67 visualizações
GigaIO: The March of Composability Onward to Memory with CXL por CXL Forum
GigaIO: The March of Composability Onward to Memory with CXLGigaIO: The March of Composability Onward to Memory with CXL
GigaIO: The March of Composability Onward to Memory with CXL
CXL Forum126 visualizações
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... por Vadym Kazulkin
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
Vadym Kazulkin70 visualizações
Future of Learning - Yap Aye Wee.pdf por NUS-ISS
Future of Learning - Yap Aye Wee.pdfFuture of Learning - Yap Aye Wee.pdf
Future of Learning - Yap Aye Wee.pdf
NUS-ISS38 visualizações
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum... por NUS-ISS
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
NUS-ISS28 visualizações

JavaScript DOM Manipulations

  • 1. JavaScript DOM Manipulations and Events Slides By: Ynon Perek Fine me at: http://ynonperek.com Friday, April 12, 13
  • 2. The Task Read text Make web <BODY BGCOLOR='#FFFFFF' style="overflow:hidden;" LEFTMARGIN=0 MARGINWIDTH=0 TOPMARGIN=0 MARGINHEIGHT=0 CLASS="text" onload="DisplayAD();" onresize="if(typeof DZresize == 'function'){DZresize();};if(typeof dcOnResize == 'function'){dcOnResize();};if(typeof disYnetAdColOnResize == 'function'){disYnetAdColOnResize();};" lang=he><div id='divRedAlert' style='display:none;'></div><iframe id=frmRedAlert name=frmRedAlert frameborder=0 width=0 height=0 MARGINHEIGHT=0 MARGINWIDTH=0 src='/Ext/App/RedAlert/ CdaRedAlert_iframe/0,12639,84-234-208-20,00.html'></iframe><div id='ads.ozen' style='position:absolute;z-index:2;left:0;top:0;'></div><div id='ads.elvisR.1' style='position:absolute;z-index:2;right:0;top:0;'></ div><div id=mainCont style="overflow:hidden; width:100%; height:100%;" align=center ><div id='mainSpacer' style='overflow:auto;height: 100%'><script> <style>A.brightgrey:link{color:#7d7f7e} A.brightgrey:visited{color:#7d7f7e}A.brightgrey:active{color:#7d7f7e} A.brightgrey:hover{color:#f00}A.upnvl{color:#7d7f80} A.upnvl:visited{color:#7d7f80}A.upnvl:hover{color:#f00} A.btnvl{color:#7f90b0}A.btnvl:visited{color:#7f90b0} A.btnvl:hover{color:#f00}</style><table id=tbl_logos cellspacing=0 cetd width='46' align='left' style='line-height:12px;'><a href='http:// www.ynetnews.com/home/0,7340,L-3083,00.html' class='text11 btnvl'>English</a></td></tr></table></div></td><td width=11>&nbsp;</ td><td width=2 bgcolor=black></td><td width=11>&nbsp;</td><td width=132 valign=top style='direction: rtl;' class='ghci3' ><div id=divMainLogo style='margin-top:1px;'></div></td><td width=11><div style='width:11px;'></div></td><TD WIDTH=194 align=right dir=rtl VALIGN=top class='ghciTopStoryMain1' ><div dir=ltr style='height: 38px;overflow:hidden;'><IMG SRC='/Common/Files/Images/Date/12.gif' alt="12/04/2013 11:20"><IMG SRC='/Common/Files/Images/D... Friday, April 12, 13
  • 3. How Browsers Render • Each browser has a Rendering Engine • Rendering Engine takes an HTML text and produces a DOM tree Friday, April 12, 13
  • 4. Rendering Engines Engine Browser Developer Blink Google Chrome Google Gecko Mozilla Firefox Mozilla Trident IE Microsoft Apple, KDE, Nokia, Webkit Apple Safari Others Friday, April 12, 13
  • 5. How Browsers Work Parse HTML to make DOM Tree Build Render Tree from CSS Layout Elements Paint Friday, April 12, 13
  • 6. What’s a DOM Tree <html> <body> <p> Hello World </p> <div> <img src="example.png"/> </div> </body> </html> Friday, April 12, 13
  • 8. Rendering DOM Tree • A Render tree is derived from DOM tree • It’s not a 1-1 relation Friday, April 12, 13
  • 9. Browser Flow • Read page as text • Create DOM tree • Create Render tree • Paint Friday, April 12, 13
  • 10. Enter JavaScript • Read page as text • Create DOM tree JavaScript Manipulates the • Create Render tree data • Paint Friday, April 12, 13
  • 11. Enter JavaScript • JavaScript alters page load • JavaScript alters DOM Tree • JavaScript creates interactivity through events handling Friday, April 12, 13
  • 12. JavaScript and DOM <!DOCTYPE html> <html> <head>   <title></title> </head> <body> A <script> element is   <script>     var x = 5; executed in place     var y = 3;     console.log('Hello From JS');   </script>   <p>This is just some text</p> </body> </html> Friday, April 12, 13
  • 13. Q&A Browser Page Rendering Friday, April 12, 13
  • 14. Interactive Apps • Browser is a programming platform • A web application is interactive Friday, April 12, 13
  • 15. Interactivity • Browser itself is interactive • In addition: A web page is interactive • Demo Friday, April 12, 13
  • 16. Browser Events Loop Event Queue click Friday, April 12, 13
  • 17. Event Loop Wait for Events Handle Events Friday, April 12, 13
  • 18. Event Loop Wait for Events Handle Events Friday, April 12, 13
  • 19. Event Loop Wait for Events Handle Events Friday, April 12, 13
  • 20. Event Handling DOM Node + Event Handler (code) Event Friday, April 12, 13
  • 21. Code Outline • From HTML: • <a on...=”handleEvent()”> Friday, April 12, 13
  • 22. Code Outline • But this can get messy <a href="#" onclick="doclick"     onblur="doblur"     onchange="dochange"     ondblclick="dodblclick"     onmousemove="domove"     onmouseover="doover"> Too many events</a> Friday, April 12, 13
  • 23. Code Outline • From JS • Get a DOM node • Bind event to code Friday, April 12, 13
  • 24. Getting DOM Nodes • getElementById(...) • getElementsByTagName(...) • querySelector(...) - IE8 and up Friday, April 12, 13
  • 25. Browser Events • All browsers use: node.onevent = ... • IE uses: node.attachEvent(...) • Other browsers use node.addEventListener(...) Friday, April 12, 13
  • 26. Demo: Events • Write a simple page that shows alert as a response to click event • Modify to change text of element Friday, April 12, 13
  • 27. Using the Event Object • Event object includes info on the event • Print it to console for inspection   <button>Click Me</button>     <script>     var btn = document.getElementsByTagName('button')[0];     btn.onclick = function(e) {       if ( ! e ) e = window.event;         console.dir( e );     };   </script> Friday, April 12, 13
  • 28. Capturing vs. Bubbling | | / ---------------| |----------------- ---------------| |----------------- | element1 | | | | element1 | | | | -----------| |----------- | | -----------| |----------- | | |element2 / | | | |element2 | | | | | ------------------------- | | ------------------------- | | Event CAPTURING | | Event BUBBLING | ----------------------------------- ----------------------------------- Friday, April 12, 13
  • 29. Capturing vs. Bubbling | | / ---------------| |----------------- ---------------| |----------------- | element1 | | | | element1 | | | | -----------| |----------- | | -----------| |----------- | | |element2 / | | | |element2 | | | | | ------------------------- | | ------------------------- | | Event CAPTURING | | Event BUBBLING | ----------------------------------- ----------------------------------- Netscape Microsoft Friday, April 12, 13
  • 30. Capturing vs. Bubbling | | / -----------------| |--| |----------------- | element1 | | | | | | -------------| |--| |----------- | | |element2 / | | | | | -------------------------------- | | W3C event model | ------------------------------------------ Friday, April 12, 13
  • 31. Capturing vs. Bubbling • node.addEventListener takes a third parameter • true means capturing • false means bubbling • defaults to false Friday, April 12, 13
  • 32. Demo • Capture all click events using document.onclick = ... Friday, April 12, 13
  • 33. Usages • Default event handlers • Dynamic event handlers Friday, April 12, 13
  • 34. Double Handlers element1.onclick = Element2 doSomething; Element1 element2.onclick = doSomething; Friday, April 12, 13
  • 35. Double Handlers function doSomething(e) {       if ( ! e ) e = window.event; Element2         // this refers to Element1 // the current element       // for inner event: // this = element2       // for outer event: // this = element1 } Friday, April 12, 13
  • 36. Event Types Interface Events Mouse Events Form Events load, unload click, dblclick submit mousedown, mouseup, resize, scroll, reset mousemove focus, blur mouseover, mouseout Friday, April 12, 13
  • 37. Default Action • Some events also have a “default” action • For example: A link will take you to another page by default Friday, April 12, 13
  • 38. Default Action • Possible to prevent • return false from handler • Demo Friday, April 12, 13
  • 39. Q&A Handling Events Friday, April 12, 13
  • 40. Events Lab • Implement 5 duplicated input boxes • Each input box should have the same text • Change one -> all change automatically Friday, April 12, 13
  • 42. Altering Page Load • Change Document • Change DOM Tree • Change Render Tree Friday, April 12, 13
  • 43. Change Document • (Don’t) use document.write to change the document as it’s being loaded • Considered bad practice Friday, April 12, 13
  • 44. Change Document <!DOCTYPE html> <html> <head>   <title></title> </head> <body>   <script> document.write('<h1>Hello World</h1>'); </script>   <p>This is just some text</p> </body> </html> Friday, April 12, 13
  • 45. Change Document 1. Browser starts to create DOM tree body 2. Finds a script tag. script Stops to execute Friday, April 12, 13
  • 46. Change Document body 3. script added <h1> script h1 element to document Friday, April 12, 13
  • 47. Change Document body script h1 p 4. browser can continue to create the <p> Friday, April 12, 13
  • 48. Avoiding document.write • Can insert invalid content • Clobbers DOM if called after reading the document Friday, April 12, 13
  • 49. Friendlier Ways • Get a DOM node • Change it using DOM API Friday, April 12, 13
  • 50. Finding DOM Nodes Friday, April 12, 13
  • 51. DOM Traversal <body> body   <div>     <h1>Header</h1>     <p>       <img src="..." /> #text #div #text       Paragraph text       <a href="#">google</a> #text #text #h1 #text #p     </p>   </div> </body> Friday, April 12, 13
  • 52. DOM Traversal • n.childNodes[] • n.firstChild • n.lastChild • n.nextSibling • n.parentNode • n.previousSibling Friday, April 12, 13
  • 53. The (Past) Future • document.querySelector takes any CSS selector and fetches DOM element • Supported in IE8 and later Friday, April 12, 13
  • 54. DOM API • Allows • Getting info on elements • Changing element attributes • Creating new elements • Setting elements style Friday, April 12, 13
  • 55. DOM API • Use x.nodeName to get the tag name if ( this.nodeName === 'INPUT' ){   // handle input element } Friday, April 12, 13
  • 56. DOM API • Use x.nodeValue to get/set the node value a.firstChild.nodeValue = 'Go to google'; Friday, April 12, 13
  • 57. DOM API • Use getAttribute / setAttribute to change element attributes a.setAttribute('href', 'http://www.google.com'); Friday, April 12, 13
  • 58. Creating New Elements • Create elements and text nodes using document • Later you can add them to the DOM document.createElement('P'); document.createTextNode('Hello World'); Friday, April 12, 13
  • 59. Creating New Elements • Insert new nodes by manipulating existing // append y to x x.appendChild(y)   // insert y to x before z x.insertBefore(y,z)   // remove y from x x.removeChild(y)   // replace y with z x.replaceChild(y,z) Friday, April 12, 13
  • 60. Change Style • Use .style property to set an element style • Note style keys are almost like CSS property names p.style.backgroundColor = 'blue'; Friday, April 12, 13
  • 61. Q&A Handling Events Friday, April 12, 13
  • 62. DOM Lab • Given the HTML at: http://jsbin.com/ecitag/1/edit • Use JavaScript to: • write your name in the first <li> item of the second list • Change the H3 to H4 • Set all links to point to google.com Friday, April 12, 13
  • 63. DOM Lab • Create a Money Converter calculator • Support 3 currencies Friday, April 12, 13