SlideShare una empresa de Scribd logo
1 de 67
JavaScript APIs You’ve
    Never Heard Of
 (And some you have)

                Nicholas C. Zakas
                        @slicknet
Who’s this guy?
flickr.com/photos/vbillings/172124448
                                    /
HTML5, DOM4 &
…DOM Level 2!
<ul id=“mylist”>
   <li>Item 1</li>
   <li>Item 1</li>
   <li>Item 1</li>
</ul>




                        UL




#text    LI     #text   LI   #text   LI   #text
<ul id=“mylist”>
     <li>Item 1</li>
     <li>Item 1</li>
     <li>Item 1</li>
  </ul>


  var list = document.getElementById(“mylist”);

  console.log(list.childNodes.length);          //7
  console.log(list.children.length);            //3




children
DOM4
HTMLCollection of all child nodes that are elements
<ul id=“mylist”>
     <li>Item 1</li>
     <li>Item 1</li>
     <li>Item 1</li>
  </ul>


  var list = document.getElementById(“mylist”),
      node1 = list.childNodes[0],
      child1 = list.children[0];

  console.log(node1.nodeName); //”#text”
  console.log(child1.nodeName); //”LI”



children
DOM4
HTMLCollection of all child nodes that are elements
<ul id=“mylist”>
     <!-- comment -->
     <li>Item 1</li>
     <li>Item 1</li>            IE 6-8 includes
     <li>Item 1</li>           comments in the
  </ul>                       children collection


  var list = document.getElementById(“mylist”),
      node1 = list.childNodes[0],
      child1 = list.children[0];

  console.log(node1.nodeName); //”#text”
  console.log(child1.nodeName); //”#comment”

children                                              BUG!
DOM4
HTMLCollection of all child nodes that are elements
UL

          firstChild                             lastChild




  #text      LI      #text       LI      #text       LI      #text




Element Traversal API
Defines new properties for accessing element children
9



                                UL

  firstElementChild                              lastElementChild




  #text      LI      #text       LI      #text       LI       #text




Element Traversal API
Defines new properties for accessing element children
9

  <ul id=“mylist”>
     <li>Item 1</li>
     <li>Item 1</li>
     <li>Item 1</li>
  </ul>


  var list = document.getElementById(“mylist”),
      node1 = list.firstChild,
      child1 = list.firstElementChild;

  console.log(node1.nodeName); //”#text”
  console.log(child1.nodeName); //”LI”



firstElementChild
Element Traversal API & DOM4
Point to first child node that is an element
9

  <ul id=“mylist”>
     <li>Item 1</li>
     <li>Item 1</li>
     <li>Item 1</li>
  </ul>


  var list = document.getElementById(“mylist”),
      node1= list.lastChild,
      child= list.lastElementChild;

  console.log(node1.nodeName); //”#text”
  console.log(child1.nodeName); //”LI”



lastElementChild
Element Traversal API & DOM4
Point to last child node that is an element
9




                 nextSibling

           LI                  #text                    LI




Element Traversal API
Defines new properties for accessing element children
9




           LI                  #text                    LI




                       nextElementSibling


Element Traversal API
Defines new properties for accessing element children
9




                 previousSibling

           LI                  #text                    LI




Element Traversal API
Defines new properties for accessing element children
9




           LI                  #text                    LI




                    previousElementSibling


Element Traversal API
Defines new properties for accessing element children
9

  // iterate over element children
  var child = element.firstElementChild;

  while(child) {
      process(child);
      child = child.nextElementSibling;
  }




Element Traversal API
Defines new properties for accessing element children
var element = document.getElementById(“foo”);

  if (document.body.contains(element)) {
      //do something
  }

  function isAncestor(child, maybeAncestor) {
      return maybeAncestor.contains(child);
  }

  // useful for event delegation
  if (isAncestor(event.target, list)) {
      // do something
  }

contains()
DOM4
Determines if a given element is an ancestor of another
“beforebegin”
              “afterbegin”
              “beforeend”
               “afterend”

element.insertAdjacentHTML(location, html);




                       Any valid HTML
                           string




insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>


var menu = document.getElementById("menu");




insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <p>Hello world!</p>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>


var menu = document.getElementById("menu");
menu.insertAdjacentHTML("beforebegin",
    "<p>Hello world!</p>");


insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li>Hello world!</li>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>


var menu = document.getElementById("menu");
menu.insertAdjacentHTML(“afterbegin",
    "<li>Hello world!</li>");


insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
        <li>Hello world!</li>
    </ul>
</nav>


var menu = document.getElementById("menu");
menu.insertAdjacentHTML(“beforeend",
    "<li>Hello world!</li>");


insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
    <p>Hello world!</p>
</nav>


var menu = document.getElementById("menu");
menu.insertAdjacentHTML(“afterend",
    "<p>Hello world!</p>");


insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
http://jsperf.com/insertadjacenthtml-perf/4




                                              In many cases,
                                                faster than
                                                innerHTML!




insertAdjacentHTML()
HTML5
Insert an HTML string into the DOM at a specific place
element.outerHTML = html;




                      Any valid HTML
                          string




outerHTML
HTML5
Get/set HTML for an entire element
<nav>
    <h2>Site Menu</h2>
    <ul id="menu">
        <li><a href="/">Home</a></li>
        <li><a href="/about">About</a></li>
    </ul>
</nav>


var menu = document.getElementById("menu");
var html = menu.outerHTML;




outerHTML
HTML5
Get/set HTML for an entire element
<nav>
    <h2>Site Menu</h2>
    <p>Hello world!</p>
</nav>


var menu = document.getElementById("menu");     Detached
menu.outerHTML = "<p>Hello world!</p>";        reference to
                                                   <ul>
console.log(menu.tagName);           // “UL”
console.log(menu.parentNode);        // null




outerHTML
HTML5
Get/set HTML for an entire element
9




document.implementation.createHTMLDocument(title);


                               Title of the
                               document




createHTMLDocument()
DOM Level 2
Create an invisible document
9


var doc =
      document.implementation.createHTMLDocument(“Test”);

console.log(doc.title);        // “Test”

doc.body.innerHTML = “<p>Hello world!</p>”;
var p = document.querySelector(“p”);

console.log(p.textContent);      // “Hello world!”




createHTMLDocument()
DOM Level 2
Create an invisible document
9


function isSafeHTML(html) {
    var doc =
      document.implementation.createHTMLDocument(“Test”);

    doc.body.innerHTML = html;

    return !doc.querySelector(“script,style,link,object”);
}




createHTMLDocument()
DOM Level 2
Create an invisible document
9
function sanitizeHTML(html) {
    var doc =
      document.implementation.createHTMLDocument(“Test”);

    doc.body.innerHTML = html;

    var nodes =
         doc.querySelectorAll(“script,style,link,object”);

    for (var i=0, len=nodes.length; i < len; i++) {
        nodes[i].parentNode.removeChild(nodes[i]);
    }

    return doc.body.innerHTML;
}

createHTMLDocument()
DOM Level 2
Create an invisible document
9


<input value="data" id="data-field">



var textbox = document.getElementById("data-field");
textbox.focus();

textbox.select();


textbox.setSelectionRange(1, 3);




setSelectionRange()
HTML5
Select specific parts of textbox content
9


// put caret at start
textbox.setSelectionRange(0, 0);

// put caret at end
textbox.setSelectionRange(
    textbox.value.length,
    textbox.value.length);




setSelectionRange()
HTML5
Select specific parts of textbox content
9


<input value="data" id="data-field">



var textbox = document.getElementById("data-field");
textbox.focus();
textbox.setSelectionRange(1, 3);


console.log(textbox.selectionStart);          // 1
console.log(textbox.selectionEnd);            // 3




selectionStart/selectionEnd
HTML5
Set/get the start and ending range of selection
<input value="data" id="data-field">

var textbox = document.getElementById("data-field");
textbox.focus();

var focused = document.activeElement;
console.log(focused === textbox);              // true




activeElement
HTML5
Returns the element that currently has focus
XMLHttpRequest Level 2
3         10

  var data = new FormData();

  data.append(“name”, “Nicholas”);
  data.append(“age”, 25);
  data.append(“note”, “Yeah right!”);

  var xhr = new XMLHttpRequest();
  xhr.open(“post”, “/submit”, true);

  //setup event handlers

  xhr.send(data);




FormData
XMLHttpRequest Level 2
Used to submit <form> data via XMLHttpRequest
3         10

  var data = new FormData(document.forms[0]);

  var xhr = new XMLHttpRequest();
  xhr.open(“post”, “/submit”, true);

  //setup event handlers

  xhr.send(data);




FormData
XMLHttpRequest Level 2
Used to submit <form> data via XMLHttpRequest
3          10

  <input type="file" id="photo" name="photo">

  var data = new FormData(),
      fileControl = document.getElementById("photo");

  data.append(“name”, “Nicholas”);
  data.append(“photo”, fileControl.files[0]);

  var xhr = new XMLHttpRequest();
  xhr.open(“post”, “/submit”, true);

  //setup event handlers

  xhr.send(data);

FormData
XMLHttpRequest Level 2
Used to submit <form> data via XMLHttpRequest
3              10

  var xhr = new XMLHttpRequest();
  xhr.open(“post”, “/submit”, true);

  xhr.upload.onprogress = function(event) {
      var percentage = event.loaded/event.total * 100;
      updateProgress(percentage);
  };

  xhr.send(data);




Upload Progress
XMLHttpRequest Level 2
Monitor the time to upload
3     9

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.timeout = 5000;
  xhr.ontimeout = function() {
      console.log(“Request timed out.”);
  };

  // other event handlers

  xhr.send(data);




XHR Timeouts
XMLHttpRequest Level 2
Used to stop a request after a period of time
var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.onload = function() {
      var text = xhr.responseText;
      doSomethingWith(text);
  };

  // other event handlers

  xhr.send();




XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.onload = function() {
      var xmldoc = xhr.responseXML;
      doSomethingWith(xmldoc);
  };

  // other event handlers

  xhr.send();




XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
3            10

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.responseType = "text";

  xhr.onload = function() {
      var text = xhr.response;
      doSomethingWith(text);
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
3            10

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.responseType = "document";

  xhr.onload = function() {
      var xmldoc = xhr.response;
      doSomethingWith(xmldoc);
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
3             10

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.responseType = "blob";

  xhr.onload = function() {                 Great for
      var blob = xhr.response;             downloading
      doSomethingWith(blob);                 images!
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
3                  10

  var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);
                                                          Great for
                                                        downloading
  xhr.responseType = "arraybuffer";
                                                        binary data!
  xhr.onload = function() {
      var binData = new Uint16Array(xhr.response);
      doSomethingWith(binData);
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
var xhr = new XMLHttpRequest();
  xhr.open(“get”, “/data”, true);

  xhr.responseType = "json";

  xhr.onload = function() {
      var json = xhr.response;
      doSomethingWith(json);
  };

  // other event handlers

  xhr.send();



XHR Response Types
XMLHttpRequest Level 2
Retrieve a particular type of object – not just text!
CSS in JavaScript
3                  9

  var element = document.getElementById(“foo”);

  if (element.matchesSelector(“#foo”)) {
      //do something
  }

  if (element.matchesSelector(“body .bar”)) {
      //do something
  }




matchesSelector()
Selector API Level 2
Determines if the element matches a certain CSS selector
element.mozMatchesSelector()

                 element.webkitMatchesSelector()

                 element.msMatchesSelector()

                 element.oMatchesSelector()




matchesSelector()
Selector API Level 2
Determines if the element matches a certain CSS selector
var element = document.getElementById(“foo”);

  if (element.matches(“#foo”)) {
      //do something
  }

  if (element.matches(“.bar”, element.parentNode)) {
      //do something
  }




matches ()
Selector API Level 2
Determines if the element matches a certain CSS selector
Hello!




getBoundingClientRect()
CSS Object Model Views
Determines size and location of an element in the viewport
var rect = element.getBoundingClientRect();

// all measurements in pixels relative to viewport
console.log(rect.left);
console.log(rect.top);
console.log(rect.right);      // relative to left
console.log(rect.bottom);     // relative to top

console.log(rect.width);
console.log(rect.height);



getBoundingClientRect()
CSS Object Model Views
Determines size and location of an element in the viewport
var rect = element.getBoundingClientRect();

// all measurements in pixels relative 8 adds 2 to each
                                   IE < to viewport
console.log(rect.left);           coordinate – you must
console.log(rect.top);                  subtract it
console.log(rect.right);      // relative to left
console.log(rect.bottom);     // relative to top

console.log(rect.width);
console.log(rect.height);



getBoundingClientRect()                                      BUG!
CSS Object Model Views
Determines size and location of an element in the viewport
Think clientX and
                           clientY


  var element = document.elementFromPoint(x, y);




               Element at that
              point with highest
                   z-index




elementFromPoint()
CSS Object Model Views
Return the element at a position relative to viewport
Think clientX and
                           clientY


  var element = document.elementFromPoint(x, y);




               Element at that
              point with highest
                   z-index




elementFromPoint()
CSS Object Model Views
Return the element at a position relative to viewport
10

var mql = window.matchMedia(“(max-width:600px)”);

if (mql.matches) {
    //do something
}

mql.addListener(function(mql) {

      console.log(mql.media + “ “ +
          (mql.matches ? “matches” : “doesn’t match”);

});




matchMedia()
CSS Object Model Views
Allows JavaScript to interact with CSS media queries
Review
What We Talked About
•   Element Traversal API
•   element.children
•   element.contains()
•   element.insertAdjacentHTML()
•   element.outerHTML
•   document.activeElement
•   document.implementation.createHTMLDocument()
•   element.setSelectionRange()
•   element.selectionStart
•   element.selectionEnd
What We Talked About
•   FormData
•   Upload Progress
•   XHR Timeouts
•   XHR Response Types
•   element.matchesSelector()
•   element.getBoundingClientRect()
•   document.elementFromPoint()
•   window.matchMedia()
The End
Etcetera

My blog:      nczonline.net
Twitter:      @slicknet
These Slides: slideshare.net/nzakas

Más contenido relacionado

La actualidad más candente

Time series classification
Time series classificationTime series classification
Time series classificationSung Kim
 
Session-based recommendations with recurrent neural networks
Session-based recommendations with recurrent neural networksSession-based recommendations with recurrent neural networks
Session-based recommendations with recurrent neural networksZimin Park
 
Explainable Machine Learning (Explainable ML)
Explainable Machine Learning (Explainable ML)Explainable Machine Learning (Explainable ML)
Explainable Machine Learning (Explainable ML)Hayim Makabee
 
데이터 분석가는 어떤 SKILLSET을 가져야 하는가? - 데이터 분석가 되기
데이터 분석가는 어떤 SKILLSET을 가져야 하는가?  - 데이터 분석가 되기데이터 분석가는 어떤 SKILLSET을 가져야 하는가?  - 데이터 분석가 되기
데이터 분석가는 어떤 SKILLSET을 가져야 하는가? - 데이터 분석가 되기Hui Seo
 
[PAP] 실무자를 위한 인과추론 활용 : Best Practices
[PAP] 실무자를 위한 인과추론 활용 : Best Practices[PAP] 실무자를 위한 인과추론 활용 : Best Practices
[PAP] 실무자를 위한 인과추론 활용 : Best PracticesBokyung Choi
 
PR-207: YOLOv3: An Incremental Improvement
PR-207: YOLOv3: An Incremental ImprovementPR-207: YOLOv3: An Incremental Improvement
PR-207: YOLOv3: An Incremental ImprovementJinwon Lee
 
스타트업은 데이터를 어떻게 바라봐야 할까? (개정판)
스타트업은 데이터를 어떻게 바라봐야 할까? (개정판)스타트업은 데이터를 어떻게 바라봐야 할까? (개정판)
스타트업은 데이터를 어떻게 바라봐야 할까? (개정판)Yongho Ha
 
Image Object Detection Pipeline
Image Object Detection PipelineImage Object Detection Pipeline
Image Object Detection PipelineAbhinav Dadhich
 
린분석 with 레진코믹스 ( Lean Analytics with Lezhin Comics )
린분석 with 레진코믹스 ( Lean Analytics with Lezhin Comics )린분석 with 레진코믹스 ( Lean Analytics with Lezhin Comics )
린분석 with 레진코믹스 ( Lean Analytics with Lezhin Comics )정혁 권
 
실시간 따릉이 잔여대수 예측을 통한 사용자 불만제로 프로젝트
실시간 따릉이 잔여대수 예측을 통한 사용자 불만제로 프로젝트실시간 따릉이 잔여대수 예측을 통한 사용자 불만제로 프로젝트
실시간 따릉이 잔여대수 예측을 통한 사용자 불만제로 프로젝트김인규
 
신뢰할 수 있는 A/B 테스트를 위해 알아야 할 것들
신뢰할 수 있는 A/B 테스트를 위해 알아야 할 것들신뢰할 수 있는 A/B 테스트를 위해 알아야 할 것들
신뢰할 수 있는 A/B 테스트를 위해 알아야 할 것들Minho Lee
 
인공지능추천시스템 airs개발기_모델링과시스템
인공지능추천시스템 airs개발기_모델링과시스템인공지능추천시스템 airs개발기_모델링과시스템
인공지능추천시스템 airs개발기_모델링과시스템NAVER D2
 
Data Engineering 101
Data Engineering 101Data Engineering 101
Data Engineering 101DaeMyung Kang
 
NDC 2016 김정주 - 기계학습을 활용한 게임어뷰징 검출
NDC 2016 김정주 - 기계학습을 활용한 게임어뷰징 검출 NDC 2016 김정주 - 기계학습을 활용한 게임어뷰징 검출
NDC 2016 김정주 - 기계학습을 활용한 게임어뷰징 검출 정주 김
 
프로덕트를 빠르게 개선하기 위한 베이지안 A/B 테스트
프로덕트를 빠르게 개선하기 위한 베이지안 A/B 테스트프로덕트를 빠르게 개선하기 위한 베이지안 A/B 테스트
프로덕트를 빠르게 개선하기 위한 베이지안 A/B 테스트Minho Lee
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaEdureka!
 
[PYCON KOREA 2017] Python 입문자의 Data Science(Kaggle) 도전
[PYCON KOREA 2017] Python 입문자의 Data Science(Kaggle) 도전[PYCON KOREA 2017] Python 입문자의 Data Science(Kaggle) 도전
[PYCON KOREA 2017] Python 입문자의 Data Science(Kaggle) 도전Mijeong Park
 
대용량 로그분석 Bigquery로 간단히 사용하기 (20170215 T아카데미)
대용량 로그분석 Bigquery로 간단히 사용하기 (20170215 T아카데미)대용량 로그분석 Bigquery로 간단히 사용하기 (20170215 T아카데미)
대용량 로그분석 Bigquery로 간단히 사용하기 (20170215 T아카데미)Jaikwang Lee
 
Data Visualization Tools in Python
Data Visualization Tools in PythonData Visualization Tools in Python
Data Visualization Tools in PythonRoman Merkulov
 
MS 빅데이터 서비스 및 게임사 PoC 사례 소개
MS 빅데이터 서비스 및 게임사 PoC 사례 소개MS 빅데이터 서비스 및 게임사 PoC 사례 소개
MS 빅데이터 서비스 및 게임사 PoC 사례 소개I Goo Lee
 

La actualidad más candente (20)

Time series classification
Time series classificationTime series classification
Time series classification
 
Session-based recommendations with recurrent neural networks
Session-based recommendations with recurrent neural networksSession-based recommendations with recurrent neural networks
Session-based recommendations with recurrent neural networks
 
Explainable Machine Learning (Explainable ML)
Explainable Machine Learning (Explainable ML)Explainable Machine Learning (Explainable ML)
Explainable Machine Learning (Explainable ML)
 
데이터 분석가는 어떤 SKILLSET을 가져야 하는가? - 데이터 분석가 되기
데이터 분석가는 어떤 SKILLSET을 가져야 하는가?  - 데이터 분석가 되기데이터 분석가는 어떤 SKILLSET을 가져야 하는가?  - 데이터 분석가 되기
데이터 분석가는 어떤 SKILLSET을 가져야 하는가? - 데이터 분석가 되기
 
[PAP] 실무자를 위한 인과추론 활용 : Best Practices
[PAP] 실무자를 위한 인과추론 활용 : Best Practices[PAP] 실무자를 위한 인과추론 활용 : Best Practices
[PAP] 실무자를 위한 인과추론 활용 : Best Practices
 
PR-207: YOLOv3: An Incremental Improvement
PR-207: YOLOv3: An Incremental ImprovementPR-207: YOLOv3: An Incremental Improvement
PR-207: YOLOv3: An Incremental Improvement
 
스타트업은 데이터를 어떻게 바라봐야 할까? (개정판)
스타트업은 데이터를 어떻게 바라봐야 할까? (개정판)스타트업은 데이터를 어떻게 바라봐야 할까? (개정판)
스타트업은 데이터를 어떻게 바라봐야 할까? (개정판)
 
Image Object Detection Pipeline
Image Object Detection PipelineImage Object Detection Pipeline
Image Object Detection Pipeline
 
린분석 with 레진코믹스 ( Lean Analytics with Lezhin Comics )
린분석 with 레진코믹스 ( Lean Analytics with Lezhin Comics )린분석 with 레진코믹스 ( Lean Analytics with Lezhin Comics )
린분석 with 레진코믹스 ( Lean Analytics with Lezhin Comics )
 
실시간 따릉이 잔여대수 예측을 통한 사용자 불만제로 프로젝트
실시간 따릉이 잔여대수 예측을 통한 사용자 불만제로 프로젝트실시간 따릉이 잔여대수 예측을 통한 사용자 불만제로 프로젝트
실시간 따릉이 잔여대수 예측을 통한 사용자 불만제로 프로젝트
 
신뢰할 수 있는 A/B 테스트를 위해 알아야 할 것들
신뢰할 수 있는 A/B 테스트를 위해 알아야 할 것들신뢰할 수 있는 A/B 테스트를 위해 알아야 할 것들
신뢰할 수 있는 A/B 테스트를 위해 알아야 할 것들
 
인공지능추천시스템 airs개발기_모델링과시스템
인공지능추천시스템 airs개발기_모델링과시스템인공지능추천시스템 airs개발기_모델링과시스템
인공지능추천시스템 airs개발기_모델링과시스템
 
Data Engineering 101
Data Engineering 101Data Engineering 101
Data Engineering 101
 
NDC 2016 김정주 - 기계학습을 활용한 게임어뷰징 검출
NDC 2016 김정주 - 기계학습을 활용한 게임어뷰징 검출 NDC 2016 김정주 - 기계학습을 활용한 게임어뷰징 검출
NDC 2016 김정주 - 기계학습을 활용한 게임어뷰징 검출
 
프로덕트를 빠르게 개선하기 위한 베이지안 A/B 테스트
프로덕트를 빠르게 개선하기 위한 베이지안 A/B 테스트프로덕트를 빠르게 개선하기 위한 베이지안 A/B 테스트
프로덕트를 빠르게 개선하기 위한 베이지안 A/B 테스트
 
Tableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | EdurekaTableau Tutorial for Data Science | Edureka
Tableau Tutorial for Data Science | Edureka
 
[PYCON KOREA 2017] Python 입문자의 Data Science(Kaggle) 도전
[PYCON KOREA 2017] Python 입문자의 Data Science(Kaggle) 도전[PYCON KOREA 2017] Python 입문자의 Data Science(Kaggle) 도전
[PYCON KOREA 2017] Python 입문자의 Data Science(Kaggle) 도전
 
대용량 로그분석 Bigquery로 간단히 사용하기 (20170215 T아카데미)
대용량 로그분석 Bigquery로 간단히 사용하기 (20170215 T아카데미)대용량 로그분석 Bigquery로 간단히 사용하기 (20170215 T아카데미)
대용량 로그분석 Bigquery로 간단히 사용하기 (20170215 T아카데미)
 
Data Visualization Tools in Python
Data Visualization Tools in PythonData Visualization Tools in Python
Data Visualization Tools in Python
 
MS 빅데이터 서비스 및 게임사 PoC 사례 소개
MS 빅데이터 서비스 및 게임사 PoC 사례 소개MS 빅데이터 서비스 및 게임사 PoC 사례 소개
MS 빅데이터 서비스 및 게임사 PoC 사례 소개
 

Destacado

Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceNicholas Zakas
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Nicholas Zakas
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)Nicholas Zakas
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScriptNicholas Zakas
 
High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010Nicholas Zakas
 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)Nicholas Zakas
 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! HomepageNicholas Zakas
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed BumpsNicholas Zakas
 
Functional Programming with Ruby
Functional Programming with RubyFunctional Programming with Ruby
Functional Programming with Rubytokland
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)Partnered Health
 
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"mamazin
 
Javascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsJavascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsNet7
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Nicholas Zakas
 
Social Shop Research Overview
Social Shop Research OverviewSocial Shop Research Overview
Social Shop Research OverviewLeo Burnett
 

Destacado (20)

Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
The Pointerless Web
The Pointerless WebThe Pointerless Web
The Pointerless Web
 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
 
High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010
 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)
 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! Homepage
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
 
Functional Programming with Ruby
Functional Programming with RubyFunctional Programming with Ruby
Functional Programming with Ruby
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"
Инструкция по сборке конструктора Brick арт. 908 "Пожарная спецтехника"
 
Javascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsJavascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basics
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Social Shop Research Overview
Social Shop Research OverviewSocial Shop Research Overview
Social Shop Research Overview
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 

Similar a JavaScript APIs you’ve never heard of (and some you have)

INTRODUCTION TO DOM AND DOM TREE
INTRODUCTION TO DOM AND DOM TREEINTRODUCTION TO DOM AND DOM TREE
INTRODUCTION TO DOM AND DOM TREEsystematiclab
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jqueryKostas Mavridis
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Introduction to javascript and yoolkui
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkuiKhou Suylong
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajaxbaygross
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7Zsolt Tasnadi
 
Getting Started with DOM
Getting Started with DOMGetting Started with DOM
Getting Started with DOMHernan Mammana
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulationborkweb
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETJames Johnson
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginnersIsfand yar Khan
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranRobert Nyman
 

Similar a JavaScript APIs you’ve never heard of (and some you have) (20)

Java script
Java scriptJava script
Java script
 
Automating Ievb
Automating IevbAutomating Ievb
Automating Ievb
 
INTRODUCTION TO DOM AND DOM TREE
INTRODUCTION TO DOM AND DOM TREEINTRODUCTION TO DOM AND DOM TREE
INTRODUCTION TO DOM AND DOM TREE
 
Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Introduction to javascript and yoolkui
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkui
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
Diving into php
Diving into phpDiving into php
Diving into php
 
DOM and Events
DOM and EventsDOM and Events
DOM and Events
 
JQuery
JQueryJQuery
JQuery
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 
Getting Started with DOM
Getting Started with DOMGetting Started with DOM
Getting Started with DOM
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
Jquery-overview
Jquery-overviewJquery-overview
Jquery-overview
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NET
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginners
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
 

Más de Nicholas Zakas

Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!Nicholas Zakas
 
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceNicholas Zakas
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011Nicholas Zakas
 
High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)Nicholas Zakas
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Nicholas Zakas
 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Nicholas Zakas
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)Nicholas Zakas
 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas Zakas
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010Nicholas Zakas
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010Nicholas Zakas
 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorNicholas Zakas
 
Speed Up Your JavaScript
Speed Up Your JavaScriptSpeed Up Your JavaScript
Speed Up Your JavaScriptNicholas Zakas
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScriptNicholas Zakas
 
JavaScript Variable Performance
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable PerformanceNicholas Zakas
 
The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3Nicholas Zakas
 
Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)Nicholas Zakas
 

Más de Nicholas Zakas (17)

Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
 
JavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
 
High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
 
Nicholas' Performance Talk at Google
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at Google
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
 
Responsive interfaces
Responsive interfacesResponsive interfaces
Responsive interfaces
 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI Compressor
 
Speed Up Your JavaScript
Speed Up Your JavaScriptSpeed Up Your JavaScript
Speed Up Your JavaScript
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 
JavaScript Variable Performance
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable Performance
 
The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3
 
Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)
 

JavaScript APIs you’ve never heard of (and some you have)

  • 1. JavaScript APIs You’ve Never Heard Of (And some you have) Nicholas C. Zakas @slicknet
  • 3.
  • 6.
  • 7. <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> UL #text LI #text LI #text LI #text
  • 8. <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> var list = document.getElementById(“mylist”); console.log(list.childNodes.length); //7 console.log(list.children.length); //3 children DOM4 HTMLCollection of all child nodes that are elements
  • 9. <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> var list = document.getElementById(“mylist”), node1 = list.childNodes[0], child1 = list.children[0]; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” children DOM4 HTMLCollection of all child nodes that are elements
  • 10. <ul id=“mylist”> <!-- comment --> <li>Item 1</li> <li>Item 1</li> IE 6-8 includes <li>Item 1</li> comments in the </ul> children collection var list = document.getElementById(“mylist”), node1 = list.childNodes[0], child1 = list.children[0]; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”#comment” children BUG! DOM4 HTMLCollection of all child nodes that are elements
  • 11. UL firstChild lastChild #text LI #text LI #text LI #text Element Traversal API Defines new properties for accessing element children
  • 12. 9 UL firstElementChild lastElementChild #text LI #text LI #text LI #text Element Traversal API Defines new properties for accessing element children
  • 13. 9 <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> var list = document.getElementById(“mylist”), node1 = list.firstChild, child1 = list.firstElementChild; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” firstElementChild Element Traversal API & DOM4 Point to first child node that is an element
  • 14. 9 <ul id=“mylist”> <li>Item 1</li> <li>Item 1</li> <li>Item 1</li> </ul> var list = document.getElementById(“mylist”), node1= list.lastChild, child= list.lastElementChild; console.log(node1.nodeName); //”#text” console.log(child1.nodeName); //”LI” lastElementChild Element Traversal API & DOM4 Point to last child node that is an element
  • 15. 9 nextSibling LI #text LI Element Traversal API Defines new properties for accessing element children
  • 16. 9 LI #text LI nextElementSibling Element Traversal API Defines new properties for accessing element children
  • 17. 9 previousSibling LI #text LI Element Traversal API Defines new properties for accessing element children
  • 18. 9 LI #text LI previousElementSibling Element Traversal API Defines new properties for accessing element children
  • 19. 9 // iterate over element children var child = element.firstElementChild; while(child) { process(child); child = child.nextElementSibling; } Element Traversal API Defines new properties for accessing element children
  • 20. var element = document.getElementById(“foo”); if (document.body.contains(element)) { //do something } function isAncestor(child, maybeAncestor) { return maybeAncestor.contains(child); } // useful for event delegation if (isAncestor(event.target, list)) { // do something } contains() DOM4 Determines if a given element is an ancestor of another
  • 21. “beforebegin” “afterbegin” “beforeend” “afterend” element.insertAdjacentHTML(location, html); Any valid HTML string insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 22. <nav> <h2>Site Menu</h2> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> var menu = document.getElementById("menu"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 23. <nav> <h2>Site Menu</h2> <p>Hello world!</p> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> var menu = document.getElementById("menu"); menu.insertAdjacentHTML("beforebegin", "<p>Hello world!</p>"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 24. <nav> <h2>Site Menu</h2> <ul id="menu"> <li>Hello world!</li> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“afterbegin", "<li>Hello world!</li>"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 25. <nav> <h2>Site Menu</h2> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li>Hello world!</li> </ul> </nav> var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“beforeend", "<li>Hello world!</li>"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 26. <nav> <h2>Site Menu</h2> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> <p>Hello world!</p> </nav> var menu = document.getElementById("menu"); menu.insertAdjacentHTML(“afterend", "<p>Hello world!</p>"); insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 27. http://jsperf.com/insertadjacenthtml-perf/4 In many cases, faster than innerHTML! insertAdjacentHTML() HTML5 Insert an HTML string into the DOM at a specific place
  • 28. element.outerHTML = html; Any valid HTML string outerHTML HTML5 Get/set HTML for an entire element
  • 29. <nav> <h2>Site Menu</h2> <ul id="menu"> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> var menu = document.getElementById("menu"); var html = menu.outerHTML; outerHTML HTML5 Get/set HTML for an entire element
  • 30. <nav> <h2>Site Menu</h2> <p>Hello world!</p> </nav> var menu = document.getElementById("menu"); Detached menu.outerHTML = "<p>Hello world!</p>"; reference to <ul> console.log(menu.tagName); // “UL” console.log(menu.parentNode); // null outerHTML HTML5 Get/set HTML for an entire element
  • 31. 9 document.implementation.createHTMLDocument(title); Title of the document createHTMLDocument() DOM Level 2 Create an invisible document
  • 32. 9 var doc = document.implementation.createHTMLDocument(“Test”); console.log(doc.title); // “Test” doc.body.innerHTML = “<p>Hello world!</p>”; var p = document.querySelector(“p”); console.log(p.textContent); // “Hello world!” createHTMLDocument() DOM Level 2 Create an invisible document
  • 33. 9 function isSafeHTML(html) { var doc = document.implementation.createHTMLDocument(“Test”); doc.body.innerHTML = html; return !doc.querySelector(“script,style,link,object”); } createHTMLDocument() DOM Level 2 Create an invisible document
  • 34. 9 function sanitizeHTML(html) { var doc = document.implementation.createHTMLDocument(“Test”); doc.body.innerHTML = html; var nodes = doc.querySelectorAll(“script,style,link,object”); for (var i=0, len=nodes.length; i < len; i++) { nodes[i].parentNode.removeChild(nodes[i]); } return doc.body.innerHTML; } createHTMLDocument() DOM Level 2 Create an invisible document
  • 35. 9 <input value="data" id="data-field"> var textbox = document.getElementById("data-field"); textbox.focus(); textbox.select(); textbox.setSelectionRange(1, 3); setSelectionRange() HTML5 Select specific parts of textbox content
  • 36. 9 // put caret at start textbox.setSelectionRange(0, 0); // put caret at end textbox.setSelectionRange( textbox.value.length, textbox.value.length); setSelectionRange() HTML5 Select specific parts of textbox content
  • 37. 9 <input value="data" id="data-field"> var textbox = document.getElementById("data-field"); textbox.focus(); textbox.setSelectionRange(1, 3); console.log(textbox.selectionStart); // 1 console.log(textbox.selectionEnd); // 3 selectionStart/selectionEnd HTML5 Set/get the start and ending range of selection
  • 38. <input value="data" id="data-field"> var textbox = document.getElementById("data-field"); textbox.focus(); var focused = document.activeElement; console.log(focused === textbox); // true activeElement HTML5 Returns the element that currently has focus
  • 40. 3 10 var data = new FormData(); data.append(“name”, “Nicholas”); data.append(“age”, 25); data.append(“note”, “Yeah right!”); var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); //setup event handlers xhr.send(data); FormData XMLHttpRequest Level 2 Used to submit <form> data via XMLHttpRequest
  • 41. 3 10 var data = new FormData(document.forms[0]); var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); //setup event handlers xhr.send(data); FormData XMLHttpRequest Level 2 Used to submit <form> data via XMLHttpRequest
  • 42. 3 10 <input type="file" id="photo" name="photo"> var data = new FormData(), fileControl = document.getElementById("photo"); data.append(“name”, “Nicholas”); data.append(“photo”, fileControl.files[0]); var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); //setup event handlers xhr.send(data); FormData XMLHttpRequest Level 2 Used to submit <form> data via XMLHttpRequest
  • 43. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“post”, “/submit”, true); xhr.upload.onprogress = function(event) { var percentage = event.loaded/event.total * 100; updateProgress(percentage); }; xhr.send(data); Upload Progress XMLHttpRequest Level 2 Monitor the time to upload
  • 44. 3 9 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.timeout = 5000; xhr.ontimeout = function() { console.log(“Request timed out.”); }; // other event handlers xhr.send(data); XHR Timeouts XMLHttpRequest Level 2 Used to stop a request after a period of time
  • 45. var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.onload = function() { var text = xhr.responseText; doSomethingWith(text); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 46. var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.onload = function() { var xmldoc = xhr.responseXML; doSomethingWith(xmldoc); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 47. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "text"; xhr.onload = function() { var text = xhr.response; doSomethingWith(text); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 48. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "document"; xhr.onload = function() { var xmldoc = xhr.response; doSomethingWith(xmldoc); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 49. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "blob"; xhr.onload = function() { Great for var blob = xhr.response; downloading doSomethingWith(blob); images! }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 50. 3 10 var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); Great for downloading xhr.responseType = "arraybuffer"; binary data! xhr.onload = function() { var binData = new Uint16Array(xhr.response); doSomethingWith(binData); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 51. var xhr = new XMLHttpRequest(); xhr.open(“get”, “/data”, true); xhr.responseType = "json"; xhr.onload = function() { var json = xhr.response; doSomethingWith(json); }; // other event handlers xhr.send(); XHR Response Types XMLHttpRequest Level 2 Retrieve a particular type of object – not just text!
  • 53. 3 9 var element = document.getElementById(“foo”); if (element.matchesSelector(“#foo”)) { //do something } if (element.matchesSelector(“body .bar”)) { //do something } matchesSelector() Selector API Level 2 Determines if the element matches a certain CSS selector
  • 54. element.mozMatchesSelector() element.webkitMatchesSelector() element.msMatchesSelector() element.oMatchesSelector() matchesSelector() Selector API Level 2 Determines if the element matches a certain CSS selector
  • 55.
  • 56. var element = document.getElementById(“foo”); if (element.matches(“#foo”)) { //do something } if (element.matches(“.bar”, element.parentNode)) { //do something } matches () Selector API Level 2 Determines if the element matches a certain CSS selector
  • 57. Hello! getBoundingClientRect() CSS Object Model Views Determines size and location of an element in the viewport
  • 58. var rect = element.getBoundingClientRect(); // all measurements in pixels relative to viewport console.log(rect.left); console.log(rect.top); console.log(rect.right); // relative to left console.log(rect.bottom); // relative to top console.log(rect.width); console.log(rect.height); getBoundingClientRect() CSS Object Model Views Determines size and location of an element in the viewport
  • 59. var rect = element.getBoundingClientRect(); // all measurements in pixels relative 8 adds 2 to each IE < to viewport console.log(rect.left); coordinate – you must console.log(rect.top); subtract it console.log(rect.right); // relative to left console.log(rect.bottom); // relative to top console.log(rect.width); console.log(rect.height); getBoundingClientRect() BUG! CSS Object Model Views Determines size and location of an element in the viewport
  • 60. Think clientX and clientY var element = document.elementFromPoint(x, y); Element at that point with highest z-index elementFromPoint() CSS Object Model Views Return the element at a position relative to viewport
  • 61. Think clientX and clientY var element = document.elementFromPoint(x, y); Element at that point with highest z-index elementFromPoint() CSS Object Model Views Return the element at a position relative to viewport
  • 62. 10 var mql = window.matchMedia(“(max-width:600px)”); if (mql.matches) { //do something } mql.addListener(function(mql) { console.log(mql.media + “ “ + (mql.matches ? “matches” : “doesn’t match”); }); matchMedia() CSS Object Model Views Allows JavaScript to interact with CSS media queries
  • 64. What We Talked About • Element Traversal API • element.children • element.contains() • element.insertAdjacentHTML() • element.outerHTML • document.activeElement • document.implementation.createHTMLDocument() • element.setSelectionRange() • element.selectionStart • element.selectionEnd
  • 65. What We Talked About • FormData • Upload Progress • XHR Timeouts • XHR Response Types • element.matchesSelector() • element.getBoundingClientRect() • document.elementFromPoint() • window.matchMedia()
  • 67. Etcetera My blog: nczonline.net Twitter: @slicknet These Slides: slideshare.net/nzakas