SlideShare uma empresa Scribd logo
1 de 47
Introdução ao DOM
            SAPO
   http://www.sapo.pt/
              tmn
 http://developers.tmn.pt/


     Cláudio Gamboa
         19 de Maio 2010
        <gamboa@co.sapo.pt>




                              gamboa@co.sapo.pt
DOM



     Document Object Model

” JavaScript is a fine city, but the DOM is a
  ghetto if you don't wanna lose your rims,
  better get in and out as fast as possible. ”


                                                   2

                                        gamboa@co.sapo.pt
DOM
É uma API para documentos HTML e XML.
Ele dá-nos a representação estrutural de um documento,
  dando-nos a possibilidade de alterar o conteúdo e a
  representação visual.
Basicamente, é o que faz a conexão entre as páginas e os
  scripts.
Todas as propriedades, métodos e eventos estão disponíveis
  para os web developers e para fazer a sua manipulação é
  disponibilizado por objectos.
A manipulação do DOM é feita, na maioria dos casos, por
  JavaScript.


                                                                 3

                                                      gamboa@co.sapo.pt
DOM
[#document] - document                  <html>
  |                                         <head>
  +-[HTML] - document.documentElement       </head>
     |
                                            <body>
     +-[HEAD]
     |
                                                <h1>head 1</h1>
     +-[BODY] - document.body                   <p>paragraph 1</p>
       |                                        <h2>head 2</h2>
       +-[H1]                                   <p>paragraph 2</p>
       | |                                  </body>
       | +-[#text]                      </html>
       |
       +-[P]
       | |
       | +-[#text]
       |
       +-[H2]
       | |
       | +-[#text]
       |
       +-[P]
         |
                                                                       4
         +-[#text]
                                                            gamboa@co.sapo.pt
DOM



Navegar no DOM




                            5

                 gamboa@co.sapo.pt
DOM


    document.getElementById('id');
    [object HTML_Node_Element]


    document.getElementsByName('name');
    [object HTMLCollection]


    elm.getElementsByTagName('nodeName');
    [object HTMLCollection]




                                                       6

                                            gamboa@co.sapo.pt
DOM
                               ...
                               <div id="div_id">
                                   <span id=”span_id”>some text</span>
                               </div>
                               ...



    document.getElementById('div_id');
    [object HTMLDivElement]


    document.getElementById('span_id');
    [object HTMLSpanElement]




                                                                          7

                                                               gamboa@co.sapo.pt
DOM
                     ...
                     <input type=”radio” name=”r_name” value=”1” /> 1
                     <input type=”radio” name=”r_name” value=”2” /> 2
                     <input type=”radio” name=”r_name” value=”3” /> 3
                     ...



    document.getElementsByName('r_name');
    [object HTMLCollection]
        [
             [object HTMLInputElement],
             [object HTMLInputElement],
             [object HTMLInputElement]
        ]




                                                                         8

                                                              gamboa@co.sapo.pt
DOM
                                            ...
                                            <h1>head</h1>
                                            <div>div 1</div>
                                            <div>div 2</div>
                                            <div id=”div_elm”>
                                                <p>div 3</p>
                                                <div>div 4</div>
                                            </div>
                                            ...


    document.body.getElementsByTagName('div');
    [object HTMLCollection]
        [
             [object HTMLDivElement], // div 1
             [object HTMLDivElement], // div 2
             [object HTMLDivElement], // div id=div_elm (inc div 4)
             [object HTMLDivElement]   // div 4
        ]
                                                                                 9

                                                                      gamboa@co.sapo.pt
DOM
                                              ...
                                              <h1>head</h1>
                                              <div>div 1</div>
                                              <div>div 2</div>
                                              <div id=”div_elm”>
                                                  <p>div 3</p>
                                                  <div>div 4</div>
                                              </div>
                                              ...


    document.body.getElementsByTagName('*');
    [object HTMLCollection]
        [
             [object HTMLHeadingElement],      // head
             [object HTMLDivElement],          // div 1
             [object HTMLDivElement],          // div 2
             [object HTMLDivElement],          // div id=div_elm (inc p & div 4)
             [object HTMLParagraphElement],    // p
             [object HTMLDivElement]           // div 4                         10
        ]
                                                                      gamboa@co.sapo.pt
DOM
                                       ...
                                       <h1>head</h1>
                                       <div>div 1</div>
                                       <div>div 2</div>
                                       <div id=”div_elm”>
                                           <p>div 3</p>
                                           <div>div 4</div>
                                       </div>
                                       ...


    var elm = document.getElementById('div_elm');
elm.getElementsByTagName('div');
    [object HTMLCollection]
        [
             [object HTMLDivElement]    // div 4
        ]


                                                                        11

                                                              gamboa@co.sapo.pt
DOM


    node.childNodes

    node.firstChild

    node.lastChild

    node.nextSibling

    node.previousSibling

    node.parentNode



                                       12

                             gamboa@co.sapo.pt
DOM
                                           <body>
                                              <h1>head</h1>
                                              <div>div 1</div>
                                              <div>div 2</div>
                                              <div id=”div_elm”>
                                                  <p>div 3</p>
                                                  <div>div 4</div>
                                              </div>
                                           </body>


    document.body.childNodes;
    [object NodeList]

       [
           [object   Text]                 //   n *
           [object   HTMLHeadingElement]   //   H1
           [object   Text]                 //   n *
           [object   HTMLDivElement]       //   DIV 1
           [object   Text]                 //   n *
           [object   HTMLDivElement]       //   DIV 2
           [object   Text]                 //   n *
           [object   HTMLDivElement]       //   DIV id=div_elm
                                                                           13
           [object   Text]                 //   n *
       ]                                                         gamboa@co.sapo.pt
DOM
                                        <body>
                                           <h1>head</h1>
                                           <div>div 1</div>
                                           <div>div 2</div>
                                           <div id=”div_elm”>
                                               <p>div 3</p>
                                               <div>div 4</div>
                                           </div>
                                        </body>


    document.body.firstChild;
    [object HTMLHeadingElement] // H1




                                                                        14

                                                              gamboa@co.sapo.pt
DOM
                                            <body>
                                               <h1>head</h1>
                                               <div>div 1</div>
                                               <div>div 2</div>
                                               <div id=”div_elm”>
                                                   <p>div 3</p>
                                                   <div>div 4</div>
                                               </div>
                                            </body>


    document.body.lastChild;
    [object HTMLDivElement] // DIV id=div_elm




                                                                            15

                                                                  gamboa@co.sapo.pt
DOM
                                             <body>
                                                <h1>head</h1>
                                                <div>div 1</div>
                                                <div>div 2</div>
                                                <div id=”div_elm”>
                                                    <p>div 3</p>
                                                    <div>div 4</div>
                                                </div>
                                             </body>


    document.body.firstChild.nextSibling;
    [object HTMLDivElement] // DIV (div 1)




                                                                             16

                                                                   gamboa@co.sapo.pt
DOM
                                             <body>
                                                <h1>head</h1>
                                                <div>div 1</div>
                                                <div>div 2</div>
                                                <div id=”div_elm”>
                                                    <p>div 3</p>
                                                    <div>div 4</div>
                                                </div>
                                             </body>


    document.body.lastChild.previousSibling;
    [object HTMLDivElement] // DIV (div 2)




                                                                             17

                                                                   gamboa@co.sapo.pt
DOM
                                      <body>
                                         <h1>head</h1>
                                         <div>div 1</div>
                                         <div>div 2</div>
                                         <div id=”div_elm”>
                                             <p>div 3</p>
                                             <div id=”div_4”>div 4</div>
                                         </div>
                                      </body>


    document.getElementById('div_4').parentNode;
    [object HTMLDivElement] // DIV (div id=div_elm)




                                                                          18

                                                                gamboa@co.sapo.pt
DOM



Manipulação do DOM




                               19

                     gamboa@co.sapo.pt
DOM


  Criar, adicionar,
remover e substituir
 elementos no DOM



                                 20

                       gamboa@co.sapo.pt
DOM


    Criar
        document.createElement('nodeName');
        document.createTextNode('string');
       var elmDiv = document.createElement('div');

       elmDiv // [object HTMLDivElement]

       ---------------------------------------------------------

       var textNode = document.createTextNode('my text');

       textNode // [object Text]




                                                                             21

                                                                   gamboa@co.sapo.pt
DOM


    Clonar                                        <div id=”div_id”>
                                                     <p>paragraph</p>
                                                     <div>div</div>
       elm.cloneNode(false);                      </div>
       elm.cloneNode(true);
      var elmDiv = document.getElementById('div_id');


                                                  <div id=”div_id”>
      var clonedDiv = elmDiv.cloneNode(false);    </div>
      -----------------------------------------
                                                  <div id=”div_id”>
      var clonedDiv = elmDiv.cloneNode(true);        <p>paragraph</p>
                                                     <div>div</div>
                                                  </div>
                                                                           22

                                                                 gamboa@co.sapo.pt
DOM
                                                  <div id=”div_id”>
                                                     <p>text</p>
                                                  </div>

    Adicionar
       elm.appendChild(newElm);


       var elmDiv = document.getElementById('div_id');

       var newP = document.createElement('p');
       var newText = document.createTextNode('some text');


       newP.appendChild(newText);
                                                  <div id=”div_id”>
       elmDiv.appendChild(newP);                     <p>text</p>
                                                     <p>some text</p>
                                                  </div>
                                                                           23

                                                                 gamboa@co.sapo.pt
DOM
                                             <div id=”div_id”>
                                                <p id=”p_id”>text</p>
                                             </div>

    Adicionar antes
       elm.insertBefore(newElm, nextElm);


       var elmDiv = document.getElementById('div_id');
       var elmP = document.getElementById('p_id');

       var newDiv = document.createElement('div');


       elmDiv.insertBefore(newDiv, elmP);    <div id=”div_id”>
                                                <div></div>
                                                <p id=”p_id”>text</p>
                                             </div>

                                                                          24

                                                                gamboa@co.sapo.pt
DOM

                                             <div id=”div_id”>

    Remover                                     <p id=”p_id”>text</p>
                                             </div>
       elm.removeChild(oldElm);


      var elmDiv = document.getElementById('div_id');
      var elmP = document.getElementById('p_id');


      elmDiv.removeChild(elmP);
                                                  <div id=”div_id”>
      ou ”suicídio”
                                                  </div>
      elmP.parentNode.removeChild(elmP);




                                                                          25

                                                                gamboa@co.sapo.pt
DOM
                                                     <div id=”div_id”>
                                                        <p id=”p_id”>text</p>

    Substituir                                       </div>

        elm.replaceChild(newElm, oldElm);


       var elmDiv = document.getElementById('div_id');
       var elmP = document.getElementById('p_id');

       var newDiv = document.createElement('div');


       elmDiv.replaceChild(newDiv, elmP);                <div id=”div_id”>
                                                            <div></div>
       ou                                                </div>
       elmP.parentNode.replaceChild(newDiv, elmP);

                                                                              26

                                                                    gamboa@co.sapo.pt
DOM
                                                 <div id=”div_id”>
                                                 </div>

    innerHTML
         elm.innerHTML = 'new HTML string';
var elmDiv = document.getElementById('div_id');

var newHTML = '<div>new div</div><p>text</p>';
var moreHTML = '<p>more text</p>';

elmDiv.innerHTML = newHTML;      <div id=”div_id”>
                                    <div>new div</div>
append                              <p>text</p>
                                 </div>

elmDiv.innerHTML += moreHTML;    <div id=”div_id”>
                                    <div>new div</div>
                                    <p>text</p>
                                    <p>more text</p>                           27
                                 </div>
                                                                     gamboa@co.sapo.pt
DOM


Manipular elementos
      no DOM




                                28

                      gamboa@co.sapo.pt
DOM
                                                     <div id=”d_id”>
                                                     </div>

    Definir propriedades/atributos
        elm.setAttribute('atributo', 'valor');
        elm.atributo = 'valor';

var elmDiv = document.getElementById('d_id');
ou
var newDiv = document.createElement('div');


elmDiv.setAttribute('class', 'd_class');
ou
newDiv.id = 'd_id';
                                           <div id=”d_id” class=”d_class”>
newDiv.className = 'd_class';              </div>


                                                                           29

                                                                 gamboa@co.sapo.pt
DOM


     Ler propriedades/atributos
        elm.getAttribute('atributo');
        elm.atributo;                         <div id=”d_id” class=”d_class”>
                                              </div>

var elmDiv = document.getElementById('d_id');


elmDiv.getAttribute('id');       // d_id
elmDiv.getAttribute('class');    // d_class

ou

elmDiv.id;          // d_id
elmDiv.className;   // d_class

                                                                              30

                                                                    gamboa@co.sapo.pt
DOM
                                                <div id=”d_id”>
                                                </div>

    Definir estilos
        elm.style.estiloParaDefinir = 'valor';


var elmDiv = document.getElementById('d_id');

elmDiv.style.position = 'absolute';
elmDiv.style.fontSize = '15px';


<div id=”d_id” style=”position: absolute; font-size: 15px”>
</div>


                                                                     31

                                                           gamboa@co.sapo.pt
DOM

    ...
          
              É capaz de ser hora de comer...


              var sInt = setInterval(function() {
                              comer();
                              falar();
                           }, 1000);

              setTimeout(function(){
                              clearInterval(sInt);
                              pensarEmVoltarPraSala();
                           }, 10 * 60 * 1000);

              setTimeout(function(){
                              voltarPraSala();
                           }, 15 * 60 * 1000);
                                                                   32

                                                         gamboa@co.sapo.pt
DOM



Eventos




                    33

          gamboa@co.sapo.pt
DOM - Events


    Lista de eventos

     ●   click            ●   focus      ●   load
     ●   dblclick         ●   blur       ●   unload
     ●   mousedown        ●   change     ●   beforeunload
     ●   mouseup          ●   keydown
     ●   mousemove        ●   keyup
     ●   mouseover        ●   keypress
     ●   mouseout         ●   reset
     ●   contextmenu      ●   submit



                                 ...

                          muitos mais

                                                                      34

                                                            gamboa@co.sapo.pt
DOM - Events

     Attach de eventos
         elm.'on'+event = handler_f;
         elm.attachEvent('on'+event, handler_f);
         elm.addEventListener(event, handler_f, false);
var button = document.createElement('input');
button.type = 'button';
button.value = 'OK';
var handler_f = function(e) {
                    e = e || event;
                    alert('Hello World');
                };
                                                                OK
     button.onclick   = handler_f;
ou
                                                                             Click
     if(button.attachEvent) {
         button.attachEvent('onclick', handler_f);
                                                               // Hello World
     } else {
         button.addEventListener('click', handler_f, false);
     }                                                                         35

                                                                     gamboa@co.sapo.pt
DOM - Events

    Attach de eventos
        Usando frameworks - LibSAPO.js
var button = document.createElement('input');
button.type = 'button';
button.value = 'OK';
var handler_f = function(e) {
                    e = e || event;
                    alert('Hello World');
                };



SAPO.Dom.Event.observe(button, 'click', handler_f);
                                                       OK
                                                                    Click

                                                      // Hello World

                                                                      36

                                                            gamboa@co.sapo.pt
DOM - Events

    Captura de eventos

var button = document.createElement('input');
button.value = 'OK';

var handler_f = function(e) {
                    e = e || event;

                    var elm = e.target || e.srcElement;

                    alert(elm.value);
               };


if(button.attachEvent) {                                  OK
    button.attachEvent('onclick', handler_f);
} else {                                                             Click
    button.addEventListener('click', handler_f, false);
}
                                                          // OK

                                                                         37

                                                               gamboa@co.sapo.pt
DOM - Events

    Captura de eventos
        Usando frameworks - LibSAPO.js
var button = document.createElement('input');
button.type = 'button';
button.value = 'OK';

var handler_f = function(e) {
                    e = e || event;

                    var elm = SAPO.Dom.Event.element(e);

                    alert(elm.value);
               };
                                                           OK
                                                                      Click
SAPO.Dom.Event.observe(button, 'click', handler_f);


                                                           // OK

                                                                          38

                                                                gamboa@co.sapo.pt
DOM - Events
   
       Cancelar eventos                             var cancelEvent = function(e) {
                                                        if(e.cancelBubble !== null) {
                                                            e.cancelBubble = true;
var elmA = document.createElement('a');                 }
elmA.href = 'http://www.sapo.pt/';                      if(e.stopPropagation) {
                                                           e.stopPropagation();
                                                        }
var handler_f = function(e) {                           if(e.preventDefault) {
                    e = e || event;                         e.preventDefault();
                    cancelEvent(e);                     }
                    alert('link clicked');              if(window.event) {
                };                                          e.returnValue = false;
elmA.addEventListener('click', handler_f, false);       }
                                                        if(e.cancel !== null) {
                                                            e.cancel = true;
                                                        }
                                                    };




                                                                                  39

                                                                        gamboa@co.sapo.pt
DOM - Events

    Cancelar eventos
          
              Usando frameworks - LibSAPO.js
    var elmA = document.createElement('a');
    elmA.href = 'http://www.sapo.pt/';


    var handler_f = function(e) {
                        e = e || event;
                        SAPO.Dom.Event.stop(e);
                        alert('link clicked');
                    };


    SAPO.Dom.Event.observe(elmA, 'click', handler_f);




           link clicked            redirect             www.sapo.pt
                                                                                40

                                                                      gamboa@co.sapo.pt
LibSAPO.js



LibSAPO.js




                       41

             gamboa@co.sapo.pt
LibSAPO.js



http://js.sapo.pt/


    check out
   Library API
                               42

                     gamboa@co.sapo.pt
LibSAPO.js

    SAPO

    SAPO.Utility.*

    SAPO.Dom.Element.*

    SAPO.Dom.Event.*

    SAPO.Dom.Css.*

    SAPO.Dom.Selector.*

    SAPO.Communication.Ajax()

                                          43

                                gamboa@co.sapo.pt
LibSAPO.js

    SAPO

                 http://js.sapo.pt/SAPO/




        http://js.sapo.pt/SAPO/Namespace/Class/
     http://js.sapo.pt/SAPO/Namespace/Class/sample/




                                                            44

                                                  gamboa@co.sapo.pt
LibSAPO.js
SAPO;
  SAPO.require();
                                          new SAPO.Communication.Ajax();
          SAPO.Dom.Event.observe();
                                         SAPO.Dom.Event.pointer();
   SAPO.Dom.Event.findElement();
                                    SAPO.Dom.Css.addClassName();
    SAPO.Dom.Css.removeClassName();
                                                        SAPO.Dom.Event.stop();
  SAPO.Dom.Css.getStyle();   SAPO.Dom.Css.setStyle();
   SAPO.Dom.Element.get();                         SAPO.Dom.Selector.select();
                                SAPO.Dom.Element.create();
 SAPO.Utility.Date.get();
          SAPO.Utility.Crypto.md5(); SAPO.Utility.String.htmlEntitiesEncode();
SAPO.Utility.Cookie.get();           SAPO.Utility.String.trim();
SAPO.Utility.Dumper.alertDump();
                                    SAPO.Utility.Cookie.set();
     SAPO.Utility.Dumper.alertDump();           SAPO.Utility.Url.getQueryString();
                                            SAPO.Utility.Url.base64Encode();
    SAPO.Utility.Serialize.get();                                                 45

                                                                        gamboa@co.sapo.pt
DOM
ainda há mais slides




       ?
                                 46

                       gamboa@co.sapo.pt
DOM
Cláudio Gamboa


@email: gamboa@co.sapo.pt
@xmpp: claudiogamboa@sapo.pt
@_: http://www.sapo.pt


@blog: http://blog.pdvel.com/
@social: suskind                          47

                                gamboa@co.sapo.pt

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

tmn - Introdução ao DOM

  • 1. Introdução ao DOM SAPO http://www.sapo.pt/ tmn http://developers.tmn.pt/ Cláudio Gamboa 19 de Maio 2010 <gamboa@co.sapo.pt> gamboa@co.sapo.pt
  • 2. DOM Document Object Model ” JavaScript is a fine city, but the DOM is a ghetto if you don't wanna lose your rims, better get in and out as fast as possible. ” 2 gamboa@co.sapo.pt
  • 3. DOM É uma API para documentos HTML e XML. Ele dá-nos a representação estrutural de um documento, dando-nos a possibilidade de alterar o conteúdo e a representação visual. Basicamente, é o que faz a conexão entre as páginas e os scripts. Todas as propriedades, métodos e eventos estão disponíveis para os web developers e para fazer a sua manipulação é disponibilizado por objectos. A manipulação do DOM é feita, na maioria dos casos, por JavaScript. 3 gamboa@co.sapo.pt
  • 4. DOM [#document] - document <html> | <head> +-[HTML] - document.documentElement </head> | <body> +-[HEAD] | <h1>head 1</h1> +-[BODY] - document.body <p>paragraph 1</p> | <h2>head 2</h2> +-[H1] <p>paragraph 2</p> | | </body> | +-[#text] </html> | +-[P] | | | +-[#text] | +-[H2] | | | +-[#text] | +-[P] | 4 +-[#text] gamboa@co.sapo.pt
  • 5. DOM Navegar no DOM 5 gamboa@co.sapo.pt
  • 6. DOM  document.getElementById('id'); [object HTML_Node_Element]  document.getElementsByName('name'); [object HTMLCollection]  elm.getElementsByTagName('nodeName'); [object HTMLCollection] 6 gamboa@co.sapo.pt
  • 7. DOM ... <div id="div_id"> <span id=”span_id”>some text</span> </div> ...  document.getElementById('div_id'); [object HTMLDivElement]  document.getElementById('span_id'); [object HTMLSpanElement] 7 gamboa@co.sapo.pt
  • 8. DOM ... <input type=”radio” name=”r_name” value=”1” /> 1 <input type=”radio” name=”r_name” value=”2” /> 2 <input type=”radio” name=”r_name” value=”3” /> 3 ...  document.getElementsByName('r_name'); [object HTMLCollection] [ [object HTMLInputElement], [object HTMLInputElement], [object HTMLInputElement] ] 8 gamboa@co.sapo.pt
  • 9. DOM ... <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div>div 4</div> </div> ...  document.body.getElementsByTagName('div'); [object HTMLCollection] [ [object HTMLDivElement], // div 1 [object HTMLDivElement], // div 2 [object HTMLDivElement], // div id=div_elm (inc div 4) [object HTMLDivElement] // div 4 ] 9 gamboa@co.sapo.pt
  • 10. DOM ... <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div>div 4</div> </div> ...  document.body.getElementsByTagName('*'); [object HTMLCollection] [ [object HTMLHeadingElement], // head [object HTMLDivElement], // div 1 [object HTMLDivElement], // div 2 [object HTMLDivElement], // div id=div_elm (inc p & div 4) [object HTMLParagraphElement], // p [object HTMLDivElement] // div 4 10 ] gamboa@co.sapo.pt
  • 11. DOM ... <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div>div 4</div> </div> ...  var elm = document.getElementById('div_elm'); elm.getElementsByTagName('div'); [object HTMLCollection] [ [object HTMLDivElement] // div 4 ] 11 gamboa@co.sapo.pt
  • 12. DOM  node.childNodes  node.firstChild  node.lastChild  node.nextSibling  node.previousSibling  node.parentNode 12 gamboa@co.sapo.pt
  • 13. DOM <body> <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div>div 4</div> </div> </body>  document.body.childNodes; [object NodeList] [ [object Text] // n * [object HTMLHeadingElement] // H1 [object Text] // n * [object HTMLDivElement] // DIV 1 [object Text] // n * [object HTMLDivElement] // DIV 2 [object Text] // n * [object HTMLDivElement] // DIV id=div_elm 13 [object Text] // n * ] gamboa@co.sapo.pt
  • 14. DOM <body> <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div>div 4</div> </div> </body>  document.body.firstChild; [object HTMLHeadingElement] // H1 14 gamboa@co.sapo.pt
  • 15. DOM <body> <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div>div 4</div> </div> </body>  document.body.lastChild; [object HTMLDivElement] // DIV id=div_elm 15 gamboa@co.sapo.pt
  • 16. DOM <body> <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div>div 4</div> </div> </body>  document.body.firstChild.nextSibling; [object HTMLDivElement] // DIV (div 1) 16 gamboa@co.sapo.pt
  • 17. DOM <body> <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div>div 4</div> </div> </body>  document.body.lastChild.previousSibling; [object HTMLDivElement] // DIV (div 2) 17 gamboa@co.sapo.pt
  • 18. DOM <body> <h1>head</h1> <div>div 1</div> <div>div 2</div> <div id=”div_elm”> <p>div 3</p> <div id=”div_4”>div 4</div> </div> </body>  document.getElementById('div_4').parentNode; [object HTMLDivElement] // DIV (div id=div_elm) 18 gamboa@co.sapo.pt
  • 19. DOM Manipulação do DOM 19 gamboa@co.sapo.pt
  • 20. DOM Criar, adicionar, remover e substituir elementos no DOM 20 gamboa@co.sapo.pt
  • 21. DOM  Criar document.createElement('nodeName'); document.createTextNode('string'); var elmDiv = document.createElement('div'); elmDiv // [object HTMLDivElement] --------------------------------------------------------- var textNode = document.createTextNode('my text'); textNode // [object Text] 21 gamboa@co.sapo.pt
  • 22. DOM  Clonar <div id=”div_id”> <p>paragraph</p> <div>div</div> elm.cloneNode(false); </div> elm.cloneNode(true); var elmDiv = document.getElementById('div_id'); <div id=”div_id”> var clonedDiv = elmDiv.cloneNode(false); </div> ----------------------------------------- <div id=”div_id”> var clonedDiv = elmDiv.cloneNode(true); <p>paragraph</p> <div>div</div> </div> 22 gamboa@co.sapo.pt
  • 23. DOM <div id=”div_id”> <p>text</p> </div>  Adicionar elm.appendChild(newElm); var elmDiv = document.getElementById('div_id'); var newP = document.createElement('p'); var newText = document.createTextNode('some text'); newP.appendChild(newText); <div id=”div_id”> elmDiv.appendChild(newP); <p>text</p> <p>some text</p> </div> 23 gamboa@co.sapo.pt
  • 24. DOM <div id=”div_id”> <p id=”p_id”>text</p> </div>  Adicionar antes elm.insertBefore(newElm, nextElm); var elmDiv = document.getElementById('div_id'); var elmP = document.getElementById('p_id'); var newDiv = document.createElement('div'); elmDiv.insertBefore(newDiv, elmP); <div id=”div_id”> <div></div> <p id=”p_id”>text</p> </div> 24 gamboa@co.sapo.pt
  • 25. DOM <div id=”div_id”>  Remover <p id=”p_id”>text</p> </div> elm.removeChild(oldElm); var elmDiv = document.getElementById('div_id'); var elmP = document.getElementById('p_id'); elmDiv.removeChild(elmP); <div id=”div_id”> ou ”suicídio” </div> elmP.parentNode.removeChild(elmP); 25 gamboa@co.sapo.pt
  • 26. DOM <div id=”div_id”> <p id=”p_id”>text</p>  Substituir </div> elm.replaceChild(newElm, oldElm); var elmDiv = document.getElementById('div_id'); var elmP = document.getElementById('p_id'); var newDiv = document.createElement('div'); elmDiv.replaceChild(newDiv, elmP); <div id=”div_id”> <div></div> ou </div> elmP.parentNode.replaceChild(newDiv, elmP); 26 gamboa@co.sapo.pt
  • 27. DOM <div id=”div_id”> </div>  innerHTML elm.innerHTML = 'new HTML string'; var elmDiv = document.getElementById('div_id'); var newHTML = '<div>new div</div><p>text</p>'; var moreHTML = '<p>more text</p>'; elmDiv.innerHTML = newHTML; <div id=”div_id”> <div>new div</div> append <p>text</p> </div> elmDiv.innerHTML += moreHTML; <div id=”div_id”> <div>new div</div> <p>text</p> <p>more text</p> 27 </div> gamboa@co.sapo.pt
  • 28. DOM Manipular elementos no DOM 28 gamboa@co.sapo.pt
  • 29. DOM <div id=”d_id”> </div>  Definir propriedades/atributos elm.setAttribute('atributo', 'valor'); elm.atributo = 'valor'; var elmDiv = document.getElementById('d_id'); ou var newDiv = document.createElement('div'); elmDiv.setAttribute('class', 'd_class'); ou newDiv.id = 'd_id'; <div id=”d_id” class=”d_class”> newDiv.className = 'd_class'; </div> 29 gamboa@co.sapo.pt
  • 30. DOM  Ler propriedades/atributos elm.getAttribute('atributo'); elm.atributo; <div id=”d_id” class=”d_class”> </div> var elmDiv = document.getElementById('d_id'); elmDiv.getAttribute('id'); // d_id elmDiv.getAttribute('class'); // d_class ou elmDiv.id; // d_id elmDiv.className; // d_class 30 gamboa@co.sapo.pt
  • 31. DOM <div id=”d_id”> </div>  Definir estilos elm.style.estiloParaDefinir = 'valor'; var elmDiv = document.getElementById('d_id'); elmDiv.style.position = 'absolute'; elmDiv.style.fontSize = '15px'; <div id=”d_id” style=”position: absolute; font-size: 15px”> </div> 31 gamboa@co.sapo.pt
  • 32. DOM  ...  É capaz de ser hora de comer... var sInt = setInterval(function() { comer(); falar(); }, 1000); setTimeout(function(){ clearInterval(sInt); pensarEmVoltarPraSala(); }, 10 * 60 * 1000); setTimeout(function(){ voltarPraSala(); }, 15 * 60 * 1000); 32 gamboa@co.sapo.pt
  • 33. DOM Eventos 33 gamboa@co.sapo.pt
  • 34. DOM - Events  Lista de eventos ● click ● focus ● load ● dblclick ● blur ● unload ● mousedown ● change ● beforeunload ● mouseup ● keydown ● mousemove ● keyup ● mouseover ● keypress ● mouseout ● reset ● contextmenu ● submit ... muitos mais 34 gamboa@co.sapo.pt
  • 35. DOM - Events  Attach de eventos elm.'on'+event = handler_f; elm.attachEvent('on'+event, handler_f); elm.addEventListener(event, handler_f, false); var button = document.createElement('input'); button.type = 'button'; button.value = 'OK'; var handler_f = function(e) { e = e || event; alert('Hello World'); }; OK button.onclick = handler_f; ou Click if(button.attachEvent) { button.attachEvent('onclick', handler_f); // Hello World } else { button.addEventListener('click', handler_f, false); } 35 gamboa@co.sapo.pt
  • 36. DOM - Events  Attach de eventos Usando frameworks - LibSAPO.js var button = document.createElement('input'); button.type = 'button'; button.value = 'OK'; var handler_f = function(e) { e = e || event; alert('Hello World'); }; SAPO.Dom.Event.observe(button, 'click', handler_f); OK Click // Hello World 36 gamboa@co.sapo.pt
  • 37. DOM - Events  Captura de eventos var button = document.createElement('input'); button.value = 'OK'; var handler_f = function(e) { e = e || event; var elm = e.target || e.srcElement; alert(elm.value); }; if(button.attachEvent) { OK button.attachEvent('onclick', handler_f); } else { Click button.addEventListener('click', handler_f, false); } // OK 37 gamboa@co.sapo.pt
  • 38. DOM - Events  Captura de eventos Usando frameworks - LibSAPO.js var button = document.createElement('input'); button.type = 'button'; button.value = 'OK'; var handler_f = function(e) { e = e || event; var elm = SAPO.Dom.Event.element(e); alert(elm.value); }; OK Click SAPO.Dom.Event.observe(button, 'click', handler_f); // OK 38 gamboa@co.sapo.pt
  • 39. DOM - Events  Cancelar eventos var cancelEvent = function(e) { if(e.cancelBubble !== null) { e.cancelBubble = true; var elmA = document.createElement('a'); } elmA.href = 'http://www.sapo.pt/'; if(e.stopPropagation) { e.stopPropagation(); } var handler_f = function(e) { if(e.preventDefault) { e = e || event; e.preventDefault(); cancelEvent(e); } alert('link clicked'); if(window.event) { }; e.returnValue = false; elmA.addEventListener('click', handler_f, false); } if(e.cancel !== null) { e.cancel = true; } }; 39 gamboa@co.sapo.pt
  • 40. DOM - Events  Cancelar eventos  Usando frameworks - LibSAPO.js var elmA = document.createElement('a'); elmA.href = 'http://www.sapo.pt/'; var handler_f = function(e) { e = e || event; SAPO.Dom.Event.stop(e); alert('link clicked'); }; SAPO.Dom.Event.observe(elmA, 'click', handler_f); link clicked redirect www.sapo.pt 40 gamboa@co.sapo.pt
  • 41. LibSAPO.js LibSAPO.js 41 gamboa@co.sapo.pt
  • 42. LibSAPO.js http://js.sapo.pt/ check out Library API 42 gamboa@co.sapo.pt
  • 43. LibSAPO.js  SAPO  SAPO.Utility.*  SAPO.Dom.Element.*  SAPO.Dom.Event.*  SAPO.Dom.Css.*  SAPO.Dom.Selector.*  SAPO.Communication.Ajax() 43 gamboa@co.sapo.pt
  • 44. LibSAPO.js  SAPO http://js.sapo.pt/SAPO/ http://js.sapo.pt/SAPO/Namespace/Class/ http://js.sapo.pt/SAPO/Namespace/Class/sample/ 44 gamboa@co.sapo.pt
  • 45. LibSAPO.js SAPO; SAPO.require(); new SAPO.Communication.Ajax(); SAPO.Dom.Event.observe(); SAPO.Dom.Event.pointer(); SAPO.Dom.Event.findElement(); SAPO.Dom.Css.addClassName(); SAPO.Dom.Css.removeClassName(); SAPO.Dom.Event.stop(); SAPO.Dom.Css.getStyle(); SAPO.Dom.Css.setStyle(); SAPO.Dom.Element.get(); SAPO.Dom.Selector.select(); SAPO.Dom.Element.create(); SAPO.Utility.Date.get(); SAPO.Utility.Crypto.md5(); SAPO.Utility.String.htmlEntitiesEncode(); SAPO.Utility.Cookie.get(); SAPO.Utility.String.trim(); SAPO.Utility.Dumper.alertDump(); SAPO.Utility.Cookie.set(); SAPO.Utility.Dumper.alertDump(); SAPO.Utility.Url.getQueryString(); SAPO.Utility.Url.base64Encode(); SAPO.Utility.Serialize.get(); 45 gamboa@co.sapo.pt
  • 46. DOM ainda há mais slides ? 46 gamboa@co.sapo.pt
  • 47. DOM Cláudio Gamboa @email: gamboa@co.sapo.pt @xmpp: claudiogamboa@sapo.pt @_: http://www.sapo.pt @blog: http://blog.pdvel.com/ @social: suskind 47 gamboa@co.sapo.pt