SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
Javascript & the DOM
     Luca Matteis
What is the DOM?
DOM == Document Object Model
<p title=quot;The test paragraphquot;>This is a sample of some <b>HTML
you might<br>have</b> in your document</p>
                           The DOM tree:
Referencing the element nodes
document.getElementById(quot;id of divquot;)
document.getElementsByTagName(quot;divquot;)[indexOfDiv]


 We could even walk the entire DOM tree from the
                document object

window.document.childNodes[0].childNodes[1].childNodes[4]
Getting/Setting the attribute node

Easy way:
var title = element.getAttribute(quot;titlequot;);
element.setAttribute(quot;titlequot;, quot;This is an elementquot;);
                          OR:
Access the quot;attributesquot; array in each
element:

for( var x = 0; x < element.attributes.length; x++ ) {
   if( element.attributes[x].nodeName.toLowerCase() == 'title' ) {
       window.alert( 'The value of the 'title' attribute is: ' +
element.attributes[x].nodeValue );
   }
}
Creating new nodes
var div= document.createElement(quot;divquot;);
var theTextOfDiv = document.createTextNode('Some content.');
div.appendChild(theTextOfTheDIv);
document.getElementById('someElementId').appendChild(div);


- You should always use this method instead of using innerHTML
when creating new nodes.
- If you're creating lots of DIVs, cloneNode(false) it instead of re-
creating it each time, its faster.
- innerHTML is faster but you should only use it if you're HTML is
safe, maybe when you're Ajax calls return HTML and you wanna
update an element.
Events
All this means nothing without Events. They give interactivity
to your page, without them we wouldn't be able to make
Javascript do something.


When the user does something an event takes place. We can
attach an event handler to certain HTML elements.
Event handling
<a href=quot;http://link.comquot; onclick=quot;alert('hi');quot;>link</a>


This way of registering event handlers to HTML elements is
bad, they should be set entirely with javascript.


element.onclick = doSomething;


Whenever the user clicks on the HTML element, the function
doSomething() is executed.
A distinct drawback is that the onclick property can contain
only one function. This becomes a problem when you want to
register multiple event handlers for one event.
Advanced event registration
element.addEventListener('click',doSomething,false);


Now we can add as many event listeners as we want to the
element.
To remove an event handler, use the removeEventListener()
method.


Microsoft uses attachEvent(), be aware of this, or use a
framework to deal with Event registration.
Event order
If you have an element inside another element, and both
have an onclick Event, which one will fire first when you click
on them?
<div onclick=quot;doSomething();quot;>
    <div onclick=quot;doSomething();quot;>Hello</div>
</div>
                          Two Models:
Event capturing: the outer element event takes place first.
This means it starts capturing events from the outer element.
Event bubbling: the inner element event takes place first. It
starts capturing events from the inner element.


You can decide which one to use through the addEventListener(). If
its last argument is true the event handler is set for the capturing
Stop Event propagation
You might want to stop event propagation from bubbling up
when you apply an event to the quot;documentquot; for example:
  document                        element.onclick=doSomething;
                                  document.onclick =
           element                defaultFunction;




You can stop the event propagation here, if you wish. If you
don’t the event bubbles up to defaultFunction(). If the user
clicks anywhere else defaultFunction() is also executed.
Turn Event propagation off
function doSomething(e) {
  if (!e) var e = window.event;
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
}


This stops all propagation of the event in the bubbling phase.
Stopping event propagation in the capturing phase is
impossible.
The quot;thisquot; keyword
In JavaScript this always refers to the “owner” of the function
we're executing, or rather, to the object that a function is a
method of.


function doSomething() {
  alert(this);
}
When calling the doSomething() function, the owner of it is
the quot;windowquot;, therefore it will alert the window object.
Event registration takes care of the ownership, making the
HTML element (on which we are applying the Event) the
owner.
The quot;thisquot; keyword
Using inline event registration doesnt quot;copyquot; the function, it
just refers to it:
<element onclick=quot;doSomething()quot;>
in this case quot;onclickquot; is not the function doSomething, rather it
just refers to the function and tells it to run it. The quot;thisquot; in
doSomething() will refer to the window object once again.


function onclick() {
  doSomething();
}
Any Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
(Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS (Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 
jQuery
jQueryjQuery
jQuery
 
HTML and CSS crash course!
HTML and CSS crash course!HTML and CSS crash course!
HTML and CSS crash course!
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Css Display Property
Css Display PropertyCss Display Property
Css Display Property
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
HTML5
HTML5HTML5
HTML5
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 Canvas
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Types of Selectors (HTML)
Types of Selectors (HTML)Types of Selectors (HTML)
Types of Selectors (HTML)
 
Java script
Java scriptJava script
Java script
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
CSS Positioning Elements.pdf
CSS Positioning Elements.pdfCSS Positioning Elements.pdf
CSS Positioning Elements.pdf
 
HTML & CSS Masterclass
HTML & CSS MasterclassHTML & CSS Masterclass
HTML & CSS Masterclass
 

Ähnlich wie Javascript and DOM

jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
Wildan Maulana
 
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Igor Moochnick
 

Ähnlich wie Javascript and DOM (20)

Event
EventEvent
Event
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
 
Javascript Browser Events.pdf
Javascript Browser Events.pdfJavascript Browser Events.pdf
Javascript Browser Events.pdf
 
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
 
Scripting The Dom
Scripting The DomScripting The Dom
Scripting The Dom
 
Events
EventsEvents
Events
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
DOM Events
DOM EventsDOM Events
DOM Events
 
Jquery
JqueryJquery
Jquery
 
Web programming
Web programmingWeb programming
Web programming
 
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
 
Wpf Introduction
Wpf IntroductionWpf Introduction
Wpf Introduction
 
WP - Unit I.ppt
WP - Unit I.pptWP - Unit I.ppt
WP - Unit I.ppt
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 
Flex Building User Interface Components
Flex Building User Interface ComponentsFlex Building User Interface Components
Flex Building User Interface Components
 
J query
J queryJ query
J query
 

Mehr von Brian Moschel

Comet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceComet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet Service
Brian Moschel
 

Mehr von Brian Moschel (12)

A Very Biased Comparison of MVC Libraries
A Very Biased Comparison of MVC LibrariesA Very Biased Comparison of MVC Libraries
A Very Biased Comparison of MVC Libraries
 
FuncUnit
FuncUnitFuncUnit
FuncUnit
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Comet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called JabbifyComet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called Jabbify
 
Web 2.0 Expo Notes
Web 2.0 Expo NotesWeb 2.0 Expo Notes
Web 2.0 Expo Notes
 
Comet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceComet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet Service
 
Building an App with jQuery and JAXER
Building an App with jQuery and JAXERBuilding an App with jQuery and JAXER
Building an App with jQuery and JAXER
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Ajax3
Ajax3Ajax3
Ajax3
 
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScript
 
Things to avoid in JavaScript
Things to avoid in JavaScriptThings to avoid in JavaScript
Things to avoid in JavaScript
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Javascript and DOM

  • 1. Javascript & the DOM Luca Matteis
  • 2. What is the DOM? DOM == Document Object Model <p title=quot;The test paragraphquot;>This is a sample of some <b>HTML you might<br>have</b> in your document</p> The DOM tree:
  • 3. Referencing the element nodes document.getElementById(quot;id of divquot;) document.getElementsByTagName(quot;divquot;)[indexOfDiv] We could even walk the entire DOM tree from the document object window.document.childNodes[0].childNodes[1].childNodes[4]
  • 4. Getting/Setting the attribute node Easy way: var title = element.getAttribute(quot;titlequot;); element.setAttribute(quot;titlequot;, quot;This is an elementquot;); OR: Access the quot;attributesquot; array in each element: for( var x = 0; x < element.attributes.length; x++ ) { if( element.attributes[x].nodeName.toLowerCase() == 'title' ) { window.alert( 'The value of the 'title' attribute is: ' + element.attributes[x].nodeValue ); } }
  • 5. Creating new nodes var div= document.createElement(quot;divquot;); var theTextOfDiv = document.createTextNode('Some content.'); div.appendChild(theTextOfTheDIv); document.getElementById('someElementId').appendChild(div); - You should always use this method instead of using innerHTML when creating new nodes. - If you're creating lots of DIVs, cloneNode(false) it instead of re- creating it each time, its faster. - innerHTML is faster but you should only use it if you're HTML is safe, maybe when you're Ajax calls return HTML and you wanna update an element.
  • 6. Events All this means nothing without Events. They give interactivity to your page, without them we wouldn't be able to make Javascript do something. When the user does something an event takes place. We can attach an event handler to certain HTML elements.
  • 7. Event handling <a href=quot;http://link.comquot; onclick=quot;alert('hi');quot;>link</a> This way of registering event handlers to HTML elements is bad, they should be set entirely with javascript. element.onclick = doSomething; Whenever the user clicks on the HTML element, the function doSomething() is executed. A distinct drawback is that the onclick property can contain only one function. This becomes a problem when you want to register multiple event handlers for one event.
  • 8. Advanced event registration element.addEventListener('click',doSomething,false); Now we can add as many event listeners as we want to the element. To remove an event handler, use the removeEventListener() method. Microsoft uses attachEvent(), be aware of this, or use a framework to deal with Event registration.
  • 9. Event order If you have an element inside another element, and both have an onclick Event, which one will fire first when you click on them? <div onclick=quot;doSomething();quot;> <div onclick=quot;doSomething();quot;>Hello</div> </div> Two Models: Event capturing: the outer element event takes place first. This means it starts capturing events from the outer element. Event bubbling: the inner element event takes place first. It starts capturing events from the inner element. You can decide which one to use through the addEventListener(). If its last argument is true the event handler is set for the capturing
  • 10. Stop Event propagation You might want to stop event propagation from bubbling up when you apply an event to the quot;documentquot; for example: document element.onclick=doSomething; document.onclick = element defaultFunction; You can stop the event propagation here, if you wish. If you don’t the event bubbles up to defaultFunction(). If the user clicks anywhere else defaultFunction() is also executed.
  • 11. Turn Event propagation off function doSomething(e) { if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } This stops all propagation of the event in the bubbling phase. Stopping event propagation in the capturing phase is impossible.
  • 12. The quot;thisquot; keyword In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. function doSomething() { alert(this); } When calling the doSomething() function, the owner of it is the quot;windowquot;, therefore it will alert the window object. Event registration takes care of the ownership, making the HTML element (on which we are applying the Event) the owner.
  • 13. The quot;thisquot; keyword Using inline event registration doesnt quot;copyquot; the function, it just refers to it: <element onclick=quot;doSomething()quot;> in this case quot;onclickquot; is not the function doSomething, rather it just refers to the function and tells it to run it. The quot;thisquot; in doSomething() will refer to the window object once again. function onclick() { doSomething(); }