1 / 26

CSC 3084: Web Development and Programming

CSC 3084: Web Development and Programming. Chapter 9: How to Use the DOM Manipulation and Traversal Methods. Chapter Overview. By the end of this chapter, you should be able to : Use any of the DOM manipulation or traversal methods to develop jQuery applications.

babu
Download Presentation

CSC 3084: Web Development and Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSC 3084:Web Development and Programming Chapter 9: How to Use the DOM Manipulation and Traversal Methods

  2. Chapter Overview • By the end of this chapter, you should be able to: • Use any of the DOM manipulation or traversal methods to develop jQuery applications. • Describe the use of the jQuery methods for working with attributes, including class attributes. • Describe the jQuery methods for DOM replacement, insertion, cloning, wrapping, and removal. • Describe the jQuery methods for working with styles and positioning elements. • Describe the jQuery methods for tree traversal and filtering. • Explain how the jQuery end method affects object chaining.

  3. Methods for Working with Attributes attr(name)Get the value of the specified attribute attr(name, value)Set the value of the specified attribute attr(map)Sets the value of multiple attributes using name/value pairs attr(name, function)Sets the value of the named attribute to the value returned by the function removeAttr(name)Removes the named attribute

  4. Attribute Examples • Set the value of the src attribute of an image to the value of a variable:$("#image").attr("src", "book1.jpg"); • Use a map to set the values of two attributes:$("#image").attr({"src": "book1.jpg", "alt": "Book 1" } ); • Remove the id attribute from all h2 elements within the “faqs” element:$("#faqs h2").removeAttr("id");

  5. Methods for Working with Class Attributes hasClass(name)Returns true if the named class is present addClass(name)Adds the named class addClass(function)Adds the class specified by the value returns by the function removeClass(name)Removes the named class removeClass(function)Removes the class specified by the value returns by the function toggleClass(name)If the named class is present, remove it. Otherwise, add it. toggleClass(function)If the class specified by the value returned by the function is present, remove it. Otherwise, add it.

  6. Class Attribute Examples • Test whether an element has a “closed” value in its class attribute:if ($("#faqs").hasClass("closed")) { ... } • Add a class to the h2 descendants of the “faqs” element:$("#faqs h2").addClass("minus"); • Remove the “minus” class from the class attribute of the h2 descendants:$("#faqs h2").removeClass("minus");

  7. Methods for DOM Replacement val()Gets the value of the form field val(value)Sets the value of the form field val(function)Sets the value to the returned value text()Gets text of all selected elements text(textString)Sets text of all selected elements text(function)Sets text to returned value html()Get the HTML content of the element html(htmlString)Sets the HTML content to the string html(function)Sets the HTML content to the return value replaceWith(content)Replaces selected elements w/ the content replaceAll(target)Replace each target element w/ the content

  8. DOM Replacement Examples • Display all of the HTML in the aside element:alert($("aside").html()); • Put an h2 element into an aside element:$("aside").html("<h2>Table of contents</h2>"); • Replace all elements that have a class named “old” with an h2 element:$(".old").replaceWith("<h2></h2>"); • Replace all elements that have a class named “old” with an h2 element (source and target are reversed with respect to the replaceWith method):$("<h2></h2>").replaceAll(".old");

  9. Methods for DOM Insertion prepend(content)Inserts content at start of the element prependTo(target)Inserts content at start of target append(content)Inserts content at end of the element appendTo(target)Inserts content at end of target before(content) Inserts content before the element insertBefore(target) Inserts content before the target after(content) Inserts content after the element insertAfter(target) Inserts content after the target clone([withEvents]) Creates a copy of the selected elements. Boolean parameter indicates if event handlers are also copied.

  10. Methods for DOM Insertion • The prepend and append methods insert content at the start or end of the selected elements, but within the elements. • The before and after methods insert the content before or after the elected elements, not within the selected elements.

  11. Examples DOM Insertion • Insert an h2 element at the end of an aside element:$("aside").append("<h2>Table of contents</h2>"); • Insert an <a> element after the last <p> element in an article:$("article p:last").after( "<a href='#top'>Back to top</a>"); • Insert the <a> elements in an article after the h2 elements in an aside:("article a").insertAfter($("aside h2")); • Clone the <a> elements and insert them after the h2 element in an aside element:("article a").clone().insertAfter($("aside h2"));

  12. Methods for DOM Wrapping and Removal wrap(element)Wraps the given element around the selected element wrapAll(element)Wraps the given element around the selected elements wrapInner(element)Wraps the given element around thecontent of the selected element empty()Removes all the child nodes of the selected elements remove([selector])Removes the selected elements from the DOM unwrap()Removes the parents of the selected elements

  13. DOM Wrapping and Removal Examples • Wrap all <a> elements in h2 elements:$("a").wrap("<h2></h2>"); • Wrap the h1 text in an <a> element:$("article h1").wrapInner("<a id='top'></a>"); • Remove the first <a> element in an article:$("article a:first").remove();

  14. TOC Application • See JS Textbook Files\book_apps\ch09\toc\index.html and toc.js • The aside is empty to begin – the JavaScript fills the aside with content

  15. Methods for Working with Styles css(name)Get the value of the named property css(name, value)Set the value of the named property css(map)Set the values of the named properties css(name, function) Set the value to the returned value height()Get the height of the first selected element height(value)Set the height of the first selected element innerHeight()Get the height, including padding outerHeight([margin]) Get the height, including padding and borders, and margins if parameter is true width() Get the width of the first selected element width(value)Set the width of the first selected element • There are yet other methods for setting/getting the width/height. See the textbook.

  16. Style Examples • Set the CSS color property for all h2 elements to blue:$(h2).css("color", "blue"); • Use a map to set two CSS properties for all h2 elements:$(h2).css({"color": "blue", "font-size": "150%"}); • Get the height of an article element:var height = $("article").height();

  17. Methods for Positioning Elements offset()Get coords of element w.r.t. document window offset(coordinates) Sets coords. w.r.t. document window position()Get coords of element w.r.t. parentelement scrollTop()Gets position of vertical scroll bar for the selected element scrollTop(value)Sets position of vertical scroll bar scrollLeft()Gets position of horizontal scroll bar scrollLeft(value)Sets position of horizontal scroll bar

  18. Positioning Examples • Get the top offset for an article element:varoffsetTop = $("article").offset().top; • Set the offset coordinates for an aside element:varasideCoordinates = new Object();asideCoordinates.top = 200;asideCoordinates.left = 100;$("aside").offset(asideCoordinates); • Move the scroll bar for the window to the top:$(window).scrollTop(0);

  19. Enhanced TOC Application • See JS Textbook Files\book_apps\ch09\toc_enhanced • This version also requires some careful positioning of the body and aside in the CSS:body { position: relative; }aside { position: absolute; }

  20. Tree traversal methods siblings([selector])Get the siblings of the element, optionally filtered by a selector next([selector])Get the first sibling that follows the element nextAll([selector])Get all siblings that follow the element nextUntil(selector) Get all siblings that follow the element, up to but not including, the parameter prev([selector])Get the preceding sibling of the element prevAll([selector])Get all preceding siblings of the element prevUntil(selector)Get all siblings that precede the element, up to but not including, the parameter

  21. Tree traversal methods children([selector])Get the children of the element parents([selector]) Get the ancestors of the element parentsUntil(selector) Get the ancestors of the element, up to but not including, the parameter parent([selector]) Get the parent of the element offsetParent() Get the closest ancestor that is positioned closest(selector Get the first element that matches the[, context]) parameter, beginning at the current element and going up to the DOM, possibly stopping at the context element find(selector) Get the descendants of the selected element after it has been filtered by the specified selector

  22. Tree Traversal Examples • Get the previous paragraph sibling of an element:varpreviousParagraph= $("#last_heading").prev("p"); • Get the parent of an element:var parent = $("#faqs").parent(); • Get all span elements within <p> elements with an article element:$("article p").find("span").css("color", "red");

  23. Filtering Methods filter(selector)Reduces the set of selected elements to those that match the selector not(selector)Exclude those elements given by the parameter has(selector)Include only those elements that have a descendant that match the parameter eq(index)Include only the elements at the given index first()Include only the first element in the set last()Include only the last element in the set slice(start[, end])Include only those items from the set whose indexes are in the range given by the params end()Return the set of selected elements to its previous state (? we’ll see examples)

  24. Filtering Method Examples • Change a property for h2 elements in the “best” class:$("h2").filter(".best").css("color", "red"); • Change a property for all <p> elements except the ones in the “first” class:$("p").not(".first").css("text-indent", "1.5em"); • Hide all images in the “slides” element except for the one with index 0: • $("#slides img").slice(1).hide(); • The example on the next slide is part of the code for a slide show. Its purpose is to fade out the first item in the queue, fade in the second image, and then move the first item to the end of the queue, which makes the old second item the new first item.

  25. Filtering Method Examples • Work with the images in a set: $("#slides img") .first().fadeOut(1000) // fade out first img element .next().fadeIn(1000) // fade in the next element .end() // return to first element .appendTo("#slides"); // append first element // to end of set • first() changes the set of selected items to include only the first image in the group of img tags • next() changes the set to include only second image • end() resets the set back to include just the first image • appendTo() then appends the first image (not the second) to the end of the list

  26. Slide Show Application • See JS Textbook Files\book_apps\ch09\slide_show_1 and JS Textbook Files\book_apps\ch09\slide_show_2 • Here we see two ways to create the slide show application with very little code

More Related