Upgrade to Pro — share decks privately, control downloads, hide ads and more …

20 - jQuery and The DOM p2

20 - jQuery and The DOM p2

Avatar for Tony Hetrick

Tony Hetrick

March 22, 2013
Tweet

More Decks by Tony Hetrick

Other Decks in Technology

Transcript

  1. Copyright Notice … The materials (used by permission) in this

    presentation are from Web Programming Step by Step written by Marty Stepp, Jessica Miller, and Victoria Kirst. † http://www.webstepbook.com/supplements-2ed.shtml … Document's original contents are © Copyright 2012 Marty Stepp, Jessica Miller, and Victoria; revised by Anthony Hetrick. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.
  2. 1) The DOM Tree 2) The DOM and jQuery 3)

    jQuery Nodes JavaScript and DOM
  3. Types of DOM nodes … element nodes (div, p, a

    tag) … text nodes (<p>A text node</p>) <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> HTML
  4. Types of DOM nodes … attribute nodes (attribute/value pair) †

    text/attributes are children in an element node † cannot have children or attributes † not usually shown when drawing the DOM tree <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> HTML
  5. Traversing the DOM tree manually … every node's DOM object

    has the following properties: name(s) description firstChild, lastChild start/end of this node's list of children childNodes array of all this node's children nextSibling, previousSibling neighboring nodes with the same parent parentNode the element that contains this node
  6. DOM tree traversal example <p id="foo">This is a paragraph of

    text with a <a href="/path/to/another/page.html">link</a>.</p> HTML
  7. Elements vs text nodes … Q: How many children does

    the <div> have? <div> <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> </div> HTML
  8. Elements vs text nodes … Q: How many children does

    the <div> have? … A: 3 † an element node representing the <p> † two text nodes representing "\n\t" (before/after the paragraph) <div> <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> </div> HTML
  9. Elements vs text nodes … Q: How many children does

    the <p> tag have? <div> <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> </div> HTML
  10. Elements vs text nodes … Q: How many children does

    the <p> tag have? … A: 3 † A text node with the paragraph text † an element node representing the <a> † A text node containing the period <div> <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> </div> HTML
  11. Elements vs text nodes … Q: How many children does

    the <a> tag have? Attributes? <div> <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> </div> HTML
  12. Elements vs text nodes … Q: How many children does

    the <a> tag have? Attributes? … A: 1child text node † A text node with the text: “link in it” <div> <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> </div> HTML
  13. Elements vs text nodes … Q: How many children does

    the <a> tag have? Attributes? … A: 1child text node † A text node with the text: “link in it” … A: 1child attribute node † href: /path/to/page.html <div> <p> This is a paragraph of text with a <a href="/path/to/page.html">link in it</a>. </p> </div> HTML
  14. 1) The DOM Tree 2) The DOM and jQuery 3)

    jQuery Nodes JavaScript and DOM
  15. Looping over the DOM … The DOM way var elems

    = document.querySelectorAll("li"); for (var i = 0; i < elems.length; i++) { var e = elems[i]; // do stuff with e } JS
  16. Looping over the DOM $("li").each(function(idx, e) { // do stuff

    with e }); JS … The jQuery way … The DOM way var elems = document.querySelectorAll("li"); for (var i = 0; i < elems.length; i++) { var e = elems[i]; // do stuff with e } JS
  17. Inside the jQuery each loop … e is a plain

    old DOM object $("li").each(function(idx, e) { e = $(e); // do stuff with e }); JS
  18. Inside the jQuery each loop … e is a plain

    old DOM object † We can upgrade it again using $ if we want $("li").each(function(idx, e) { e = $(e); // do stuff with e }); JS
  19. Inside the jQuery each loop $("li").each(function(idx, e) { e =

    $(e); // do stuff with e }); JS … e is a plain old DOM object † We can upgrade it again using $ if we want … Since this loop is a function, just return false to exit the loop early
  20. Inside the jQuery each loop … the this keyword refers

    to the same selected element as e, so this is better jQuery $("li").each(function() { // do stuff with this }); JS
  21. Modifying DOM nodes … DOM nodes have fields that correspond

    to the attributes in HTML tags. There are a few exceptions HTML attributes DOM fields title .title id .id class .className style="prop: value" .style.prop = value
  22. Getting/setting CSS classes … The DOM's className property corresponds to

    HTML class attribute … somewhat clunky when dealing with multiple space-separated classes as one big string … className is just a string, not an array like we would want // add class 'highlight' var elem = document.getElementById("myid "); if (!elem.className) { elem.className = "highlight"; } else if (elem.className.indexOf("invalid") < 0) { elem.className += " highlight"; } JS
  23. Getting/setting CSS classes in jQuery … Has functions: addClass, removeClass,

    hasClass, toggleClass to manipulate CSS classes … similar to existing className DOM property, but don't have to manually split by spaces // add class 'highlight' if (!$("#myid").hasClass("invalid")) { $("#myid").addClass("highlight"); } JS
  24. Accessing styles in jQuery … css function of the jQuery

    object allows reading pre-existing styles … gives us the familiar font-size syntax instead of fontSize … css(property) gets the property value … css(property, value) sets the property value function biggerFont() { // make it bigger var size = parseInt($("#clickme").css("font-size")); $("#clickme").css("font-size", size + 4 + "pt"); } JS
  25. jQuery get method behavior … Getters typically operate only on

    the first of the jQuery object's selected elements. <ul> <li style="font-size: 10px">10px font size</li> <li style="font-size: 20px">20px font size</li> <li style="font-size: 30px">30px font size</li> </ul> HTML $("li").css("font-size"); // returns '10px' JS
  26. jQuery set method behavior … Setters typically operate on all

    of the selected DOM elements. <ul> <li style="font-size: 15px">10px font size</li> <li style="font-size: 15px">20px font size</li> <li style="font-size: 15px">30px font size</li> </ul> HTML $("li").css("font-size", "15px"); // set all to '15px' JS
  27. jQuery method parameters Many jQuery object methods are overloaded $("#myid").css(propertyName);

    JS getter syntax: $("#myid").css(propertyName, value); JS setter syntax:
  28. jQuery method parameters $("#myid").css(propertyName, function(idx, oldValue) { return newValue; });

    JS modifier syntax: // bad jQuery $("#main").css("top", parseInt($("#main").css("top")) + 100 + "px"); $("#main").css("top", function(idx, old) { return parseInt(old) + 100 + "px"; }); // good jQuery JS
  29. jQuery method returns … When there is no other return

    to make, jQuery methods return the same jQuery object back to you method return type $("#myid"); jQuery object $("#myid").children(); jQuery object $("#myid").css("margin-left"); String $("#myid").css("margin-left", "10px"); jQuery object $("#myid").addClass("special"); jQuery object
  30. jQuery chaining … A jQuery object allows for chaining of

    method calls. $("#main").css("color", "red"); $("#main").attr("id", "themainarea"); $("#main").addClass("special"); JS $("img") .css("color", "red") .attr("id", "themainarea") .addClass("special"); JS
  31. jQuery chaining $("img") // poor jQuery style .css("color", "red") .src

    = "foo.png"; // chain stops here JS … Do not use assignments, only function calls † Assignments stop the chaining process
  32. jQuery chaining … Do not use assignments, only function calls

    † Assignments stop the chaining process $("img") // poor jQuery style .css("color", "red") .src = "foo.png"; // chain stops here JS $("img") // good jQuery style .css("color", "red") .addClass("special") .attr("src", "foo.png"); // we could chain further right here JS
  33. More node manipulation with jQuery jQuery method functionality .hide() toggle

    CSS display: none on .show() toggle CSS display: none off .empty() remove everything inside the element, innerHTML = "" .html() get/set the innerHTML without escaping html tags .text() get/set the innerHTML, HTML escapes the text first .val() get/set the value of a form input, select, textarea, ... .height() get/set the height in pixels, returns a Number .width() get/set the width in pixels, return a Number
  34. 1) The DOM Tree 2) The DOM and jQuery 3)

    jQuery Nodes JavaScript and DOM
  35. DOM innerHTML hacking … Why not just code this way?

    document.getElementById("myid").innerHTML += "<p>A paragraph!</p>"; JS
  36. DOM innerHTML hacking document.getElementById("myid").innerHTML += "<p style='color: red; " +

    "margin-left: 50px;' " + "onclick='myOnClick();'>" + "A paragraph!</p>"; JS … Imagine that the new node is more complex:
  37. DOM innerHTML hacking document.getElementById("myid").innerHTML += "<p style='color: red; " +

    "margin-left: 50px;' " + "onclick='myOnClick();'>" + "A paragraph!</p>"; JS … Imagine that the new node is more complex: † ugly: bad style on many levels (e.g. JS code embedded within HTML)
  38. DOM innerHTML hacking document.getElementById("myid").innerHTML += "<p style='color: red; " +

    "margin-left: 50px;' " + "onclick='myOnClick();'>" + "A paragraph!</p>"; JS … Imagine that the new node is more complex: † ugly: bad style on many levels (e.g. JS code embedded within HTML) † error-prone: must carefully distinguish " and '
  39. DOM innerHTML hacking document.getElementById("myid").innerHTML += "<p style='color: red; " +

    "margin-left: 50px;' " + "onclick='myOnClick();'>" + "A paragraph!</p>"; JS … Imagine that the new node is more complex: † ugly: bad style on many levels (e.g. JS code embedded within HTML) † error-prone: must carefully distinguish " and ' † can only add at beginning or end, not in middle of child list
  40. Creating new nodes name description document.createElement("tag") creates and returns a

    new empty DOM node representing an element of that type document.createTextNode("text") creates and returns a text node containing given text
  41. Creating new nodes … merely creating a element does not

    add it to the page … you must add the new element as a child of an existing element on the page... // create a new <h2> node var newHeading = document.createElement("h2"); newHeading.innerHTML = "This is a heading"; newHeading.style.color = "green"; JS
  42. Modifying the DOM tree … Every DOM element object has

    these methods: name description appendChild(node) places given node at end of this node's child list insertBefore(new, old) places the given new node in this node's child list just before old child removeChild(node) removes given node from this node's child list replaceChild(new, old) replaces given child with new node
  43. Modifying the DOM tree … Every DOM element object has

    these methods: name description appendChild(node) places given node at end of this node's child list insertBefore(new, old) places the given new node in this node's child list just before old child removeChild(node) removes given node from this node's child list replaceChild(new, old) replaces given child with new node var p = document.createElement("p"); p.innerHTML = "A paragraph!"; document.getElementById("myid").appendChild(p); JS
  44. Removing a node from the page … each DOM object

    has a removeChild method to remove the given child from the page † Painful! var bullets = document.getElementsByTagName("li"); for (var i = 0; i < bullets.length; i++) { if (bullets[i].innerHTML.indexOf("child") >= 0) { bullets[i].parentNode.removeChild(bullets[i]); } } JS
  45. Create nodes in jQuery The $ function to the rescue

    again var newElement = $("<div>"); $("#myid").append(newElement); JS
  46. Create nodes in jQuery The $ function to the rescue

    again var newElement = $("<div>"); $("#myid").append(newElement); jQuery programmers typically 1 line it $("#myid").append($("<div>")); JS JS
  47. Remove nodes in jQuery var bullets = document.getElementsByTagName("li"); for (var

    i = 0; i < bullets.length; i++) { if (bullets[i].innerHTML.indexOf("child") >= 0) { bullets[i].parentNode.removeChild(bullets[i]); } } JS The previous example becomes this with jQuery $("li:contains('child')").remove(); JS
  48. Creating complex nodes in jQuery The terrible way, this is

    no better than innerHTML hacking $("<p id='myid' class='special'>My paragraph is awesome!</p>") JS
  49. Creating complex nodes in jQuery The terrible way, this is

    no better than innerHTML hacking $("<p id='myid' class='special'>My paragraph is awesome!</p>") The bad way, decent jQuery, but we can do better $("<p>") .attr("id", "myid") .addClass("special") .text("My paragraph is awesome!"); JS JS
  50. Creating complex nodes in jQuery $("<p>", { "id": "myid", "class":

    "special", "text": "My paragraph is awesome!" }); JS The good way
  51. jQuery $ function signatures Responding to the page ready event

    Identifying elements $(function); $("selector", [context]); JS JS
  52. jQuery $ function signatures Responding to the page ready event

    Identifying elements Upgrading DOM elements $(function); $("selector", [context]); $(elements); JS JS JS
  53. jQuery $ function signatures Responding to the page ready event

    Identifying elements Upgrading DOM elements $(function); $("selector", [context]); $(elements); Creating new elements $("<html>", [properties]); JS JS JS JS