DOM Manipulation PDF
Document Details
Uploaded by FavoriteConstructivism6060
Tags
Summary
This document provides an outline and examples for manipulating the Document Object Model (DOM) using JavaScript. The document covers topics such as selecting, traversing, modifying, and adding/deleting nodes within the DOM structure. Examples showcase DOM methods and techniques.
Full Transcript
DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Outline 2 1 DOM: Recap 2 Selecting DOM elements 3 DOM Traversal 4 Mo...
DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Outline 2 1 DOM: Recap 2 Selecting DOM elements 3 DOM Traversal 4 Modifying DOM Elements 5 Adding and removing nodes DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes DOM: Recap 3 Hierarchical representation of the contents of a web page – initialized with static HTML Can be manipulated from within the JavaScript code (both reading and writing) Allows information sharing among multiple components of web application DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes DOM as an evolving entity 4 DOM is highly dynamic! S4 S1 S0 S3 S2 S… SN S5 User Input / User Acon / Server Side DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Why Study DOM Interactions? 5 Needed for JS code to have any effect on webpage (without reloading the page) Uniform API/interface to access DOM from JS Does not depend on specific browser platform NOTE We’ll be using the native DOM APIs for many of the tasks in this lecture Though many of these can be simplified using frameworks such as jQuery, it is important to know what’s “under the hood” We assume a standards compliant browser ! DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Selecting DOM elements 6 1 DOM: Recap 2 Selecting DOM elements 3 DOM Traversal 4 Modifying DOM Elements 5 Adding and removing nodes DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Motivation: Selecting Elements 7 You can access the DOM from the object window.document and traverse it to any node However, this is slow – often you only need to manipulate specific nodes in the DOM Further, navigating to nodes this way can be error prone and fragile Will no longer work if DOM structure changes DOM structure changes from one browser to another DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Methods to Select DOM Elements 8 With a specified id With a specified tag name With a specified class With generalized CSS selector DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Method 1: getElementById 9 Used to retrieve a single element from DOM IDs are unique in the DOM (or at least must be) Returns null if no such element is found Example 1 v a r name = " Section1 " ; 2 v a r i d = document. g e t E l e m e n t B y I d ( name ) ; 3 i f ( i d == n u l l ) 4 throw new E r r o r ( " No element found : " + name ) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Method 2: getElementsByTagName 10 Retrieves multiple elements matching a given tag name (‘type’) in the DOM Returns a read-only array-like object (empty if no such elements exist in the document) Example: Hide all images in the document 1 v a r i m g s = document. getElementsByTagName ( " img " ) ; 2 f o r ( v a r i =0; i 0) { 3 // do something with the warnings list here 4 } DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Important point: Live Lists 12 Both getElementsByClassName and getElementsByTagName return live lists List can change after it is returned by the function if new elements are added to the document List cannot be changed by JavaScript code adding to it or removing from it directly (list elements can change though) Make a copy if you’re iterating through the lists (and modifying the list elements). e.g., const copy = Array.from(list) DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Selecting elements by CSS selector 13 Can also select elements using generalized CSS selectors using querySelectorAll() method Specify a selector query as argument Query results are not “live” (unlike earlier) Can subsume all the other methods querySelector() returns the first element matching the CSS query string, null otherwise DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes CSS selector syntax: Examples (Recap) 14 1 " # nav " // Any element with id = nav 2 3 " div " // Any element 4 5 ". warning " // Any element with " warning " class 6 7 " # log span " // Any < span > descendant of id =" log " 8 9 " # log > span " // Any span child element of id =" log " 10 11 " body > h1 : first - child " // first child of < body > 12 13 " div , # log " // All div elements , element with id =" log " DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Invocation on DOM subtrees 15 All of the above methods can also be invoked on DOM elements not just the document Search is confined to subtree rooted at element Example: Assume element with id=”log” exists 1 v a r l o g = document. g e t E l e m e n t B y I d ( " log " ) ; 2 v a r e r r o r = l o g. g e t E l e m e n t s B y C l a s s N a m e ( " error " ) ; 3 i f ( e r r o r. l e n g t h ==0) {... } DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Class Activity 16 Assume the page contains a div element with id id, which contains a series of images (img nodes). Write a function that takes two arguments, id and interval. At each interval, the images must be “rotated”, i.e., image0 will become image1, image1 will become image2, etc. DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Solution 17 1 function changeImages ( id , i n t e r v a l ) { 2 // Select the parent div by its id 3 c o n s t p a r e n t D i v = document. g e t E l e m e n t B y I d ( i d ) ; 4 i f ( ! p a r e n t D i v ) r e t u r n ; // Exit if the div is not found 5 6 // Function to perform the rotation of images 7 function rotateImages () { 8 c o n s t i m a g e s = p a r e n t D i v. getElementsByTagName ( ’ img ’ ) ; 9 i f ( images. l e n g t h > 0) { 10 // Remove the first image and add it to the end 11 parentDiv. appendChild ( images [ 0 ] ) ; 12 } 13 } 14 15 // Set up the interval to rotate images 16 s e t I n t e r v a l ( rotateImages , i n t e r v a l ) ; 17 } DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes DOM Traversal 18 1 DOM: Recap 2 Selecting DOM elements 3 DOM Traversal 4 Modifying DOM Elements 5 Adding and removing nodes DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Traversing the DOM 19 Since the DOM is just a tree, you can walk it the way you’d do with any other tree Typically using recursion Every browser has minor variations in implementing the DOM, so should not be sensitive to such changes Traversing DOM this way can be fragile DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Before accessing or manipulating the DOM... 20 Problem When your JS code executes, the page might not have finished loading )The DOM tree might not be fully instantiated / might change! window.onload or DOMContentLoaded Your DOM manipulation code should go inside that function 1 // load 2 window. a d d E v e n t L i s t e n e r ( ’ load ’ , f u n c t i o n ( ) { 3 c o n s o l e. l o g ( ’ All resources finished loading ! ’ ) ; 4 }) ; 5 6 // ’ D O M C o n t e n t L o a d e d 7 document. a d d E v e n t L i s t e n e r ( ’ D O M C o n t e n t L o a d e d ’ , f u n c t i o n ( ) { 8 c o n s o l e. l o g ( ’ The DOM is fully loaded and parsed , but not necessarily all resources. ’ ) ; 9 }) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Properties for DOM Traversal 21 parentNode Parent node of this one, or null childNodes A read only array-like object containing all the (live) child nodes of this one firstChild, lastChild The first and lastChild of a node, or null if it has no children nextSibling, previousSibling The next and previous siblings of a node (in the order in which they appear in the document) DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Other node properties 22 nodeType: ‘kind of node’ Document nodes: 9 Element nodes: 1 Text nodes: 3 Comment node: 8 nodeValue Textual content of Text of comment node nodeName Tag name of a node, converted to upper-case DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Example: Find a Text Node 23 We want to find the DOM node that has a certain piece of text, say “text” Return true if text is found, false otherwise We need to recursively walk the DOM looking for the text in all text nodes 1 f u n c t i o n s e a r c h ( node , t e x t ) { 2 3 }; 4 5 v a r r e s u l t = s e a r c h ( window. document , " Hello world ! " ) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Searching Recursively for a Text Node 24 1 f u n c t i o n s e a r c h ( node , t e x t ) { 2 var found = f a l s e ; 3 i f ( node. nodeType== Node.TEXT_NODE) { \\ 3 4 i f ( node. n o d e V a l u e === t e x t ) f o u n d = t r u e ; 5 } e l s e { // textNodes cannot have children 6 v a r cn = node. c h i l d N o d e s ; 7 i f ( cn ) { 8 f o r ( v a r i =0; i < cn. l e n g t h ; i ++) { 9 f o u n d = f o u n d | | s e a r c h ( cn [ i ] , t e x t ) ; 10 } 11 } 12 } 13 return found ; 14 }; 15 16 v a r r e s u l t = s e a r c h ( window. document , " Hello world ! " ) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Class Activity 25 Write a function that will traverse the DOM tree rooted at a node with a specific ‘id’, and checks if any of its sibling nodes and itself in the document is a text node, and if so, concatenates their text content and returns it. Can you generalize it so that it works for the entire subtree rooted at the sibling nodes ? DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Solution 26 1 function collectTextFromSiblingsAndSubtree ( id ) { 2 // Find the element by id 3 c o n s t s t a r t E l e m e n t = document. g e t E l e m e n t B y I d ( i d ) ; 4 i f ( ! s t a r t E l e m e n t ) r e t u r n ’ ’ ; // If the element doesn ’t exist , return an empty string 5 6 l e t t e x t C o n t e n t = ’’ ; 7 8 // Helper function to traverse the subtree 9 f u n c t i o n t r a v e r s e S u b t r e e ( node ) { 10 // Check if the current node is a text node 11 i f ( node. nodeType === Node.TEXT_NODE) { 12 t e x t C o n t e n t += node. n o d e V a l u e ; // Concatenate the text from the text node 13 } e l s e i f ( node. nodeType === Node.ELEMENT_NODE) { 14 // Recursively check the children of this node 15 A r r a y. from ( node. c h i l d N o d e s ). f o r E a c h ( t r a v e r s e S u b t r e e ) ; 16 } 17 } 18 19 // Include the text from the starting node ’s subtree 20 traverseSubtree ( startElement ) ; 21 return textContent ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Solution (siblings) 27 1 function collectTextFromSiblingsAndSubtree ( id ) { 2... 3 // Include the text from the starting node ’s subtree 4 traverseSubtree ( startElement ) ; 5 6 // Traverse sibling nodes 7 l e t s i b l i n g = s t a r t E l e m e n t. parentNode. f i r s t C h i l d ; 8 while ( s i b l i n g ) { 9 i f ( s i b l i n g !== s t a r t E l e m e n t ) { // Skip the starting node 10 t r a v e r s e S u b t r e e ( s i b l i n g ) ; // Use the helper function on the sibling ’s subtree 11 } 12 s i b l i n g = s i b l i n g. n e x t S i b l i n g ; // Move to the next sibling 13 } 14 15 return textContent ; 16 } 17 18 // Example usage 19 const textResult = collectTextFromSiblingsAndSubtree ( ’ yourElementId ’ ) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Modifying DOM Elements 28 1 DOM: Recap 2 Selecting DOM elements 3 DOM Traversal 4 Modifying DOM Elements 5 Adding and removing nodes DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Modifying DOM elements 29 DOM elements are also JavaScript Objects (in most browsers) and consequently can have their properties read and written to Can extend DOM elements by modifying their prototype objects Can add fields to the elements for keeping track of state (E.g., visited node during traversals) Can modify HTML attributes of the node such as width etc. – changes reflected in browser display DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Element Interface 30 It is bad practice to modify the Node object directly, so instead JavaScript exposes an Element interface. Objects that implement the Element interface can be modified Hierarchy of Element objects e.g., HTMLTextElement, HTMLDivElement Element object derives from Node object and has access to its properties DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Example: Changing visible elements of a node 31 Assume that you want to change the URL of an image object in the DOM with id=”myimage” after a 5 second delay to “newImage.jpg” 1 v a r myImage = document. g e t E l e m e n t B y I d ( " myimage " ) ; 2 setTimeout ( function () { 3 myImage. s r c =" newImage. jpg " ; 4 } , 5000 ) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Example: Extending DOM element’s prototype 32 Let’s add a new print method to Node that prints the text to console if it’s a text/comment node This may break some frameworks, so proceed with caution ! 1 Element. p r o t o t y p e. p r i n t = f u n c t i o n ( ) { 2 i f ( t h i s. nodeType==3 | | t h i s. nodeType==8) 3 c o n s o l e. l o g ( t h i s. nodeText ) ; 4 } DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Example: Adding new attributes to DOM elements 33 You can also add new attributes to DOM nodes, but these will not be rendered by the web browser (unless they’re HTML attributes) Caution: may break frameworks such as jQuery ! 1 v a r e = document. g e t E l e m e n t B y I d ( " myelement " ) ; 2 e. accessed = true ; 3 // accessed is a non - standard HTML attribute DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Accessing the raw HTML of a node 34 You can retrieve the raw HTML of a DOM node using it’s innerHTML property Can modify it from within JavaScript code, though this is considered bad practice and is deprecated 1 // HTML : I am a paragraph. 2 // JS code : 3 v a r e = document. g e t E l e m e n t B y I d ( " myP " ) ; 4 c o n s o l e. l o g ( e. innerHTML ) ; 5 e. innerHTML = " Don ’t do this ! " ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Class Activity 35 Add a field to each DOM element of type div that keeps track of how many times the div is accessed through the document.getElementById method, and make sure to initialize the value of this field for all div’s in the document to 0 when the document is initially loaded. DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Solution 36 1 document. a d d E v e n t L i s t e n e r ( ’ D O M C o n t e n t L o a d e d ’ , f u n c t i o n ( ) { 2 // Initialize the access count property for each div 3 c o n s t d i v s = document. getElementsByTagName ( ’ div ’ ) ; 4 f o r ( l e t i = 0 ; i < d i v s. l e n g t h ; i ++) { 5 d i v s [ i ]. accessCount = 0; 6 } 7 8 // Create a wrapper function for ‘ document. getElementById ‘ 9 c o n s t o r i g i n a l G e t E l e m e n t B y I d = document. g e t E l e m e n t B y I d. b i n d ( document ) ; 10 document. g e t E l e m e n t B y I d = f u n c t i o n ( i d ) { 11 c o n s t elem = o r i g i n a l G e t E l e m e n t B y I d ( i d ) ; 12 i f ( e l e m && e l e m. tagName === ’ DIV ’ ) { 13 elem. ac ce s sCo un t = ( elem. ac c es sCo un t | | 0) + 1 ; 14 } 15 r e t u r n elem ; 16 }; 17 }) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Adding and removing nodes 37 1 DOM: Recap 2 Selecting DOM elements 3 DOM Traversal 4 Modifying DOM Elements 5 Adding and removing nodes DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Creating New and Copying Existing DOM Nodes 38 Creating New DOM Nodes Using either document.createElement(“element”) OR document.createTextNode(“text content”) 1 v a r newNode = document. c r e a t e T e x t N o d e ( " hello " ) ; 2 v a r e l N o d e = document. c r e a t e E l e m e n t ( " h1 " ) ; Copying Existing DOM Nodes: use cloneNode Single argument can be true or false True: deep copy (recursively copy all descendants) new node can be inserted into a different document 1 v a r e x i s t i n g N o d e = document. g e t E l e m e n t B y i d ( " my " ) ; 2 v a r newNode = e x i s t i n g N o d e. c l o n e N o d e ( t r u e ) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Inserting Nodes 39 appendChild Adds a new node as a child of the node it is invoked on. node becomes lastChild insertBefore Similar, except that it inserts the node before the one that is specified as the second argument (lastChild if it’s null) 1 v a r s = document. g e t E l e m e n t B y I D ( " my " ) ; 2 s. a p p e n d C h i l d ( newNode ) ; 3 s. i n s e r t B e f o r e ( newNode , s. f i r s t C h i l d ) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Removing and replacing nodes 40 Removing a node n: removeChild 1 n. parentNode. removeChild ( n ) ; Replacing a node n with a new node: replaceChild 1 n. parentNode. r e p l a c e C h i l d ( 2 document. c r e a t e T e x t N o d e ( " [ redacted ] " ) , 3 n) ; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Example to put it all together 41 1 // function to replace a node n by making it a child of a new " div " element with id = " id " 2 function newdiv (n , i d ) { 3 v a r d i v = document. c r e a t e E l e m e n t ( " div " ) ; 4 div. id = id ; 5 n. parentNode. r e p l a c e C h i l d ( div , n ) ; 6 div. appendChild (n) ; 7 }; DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Class Activity 16 Assume the page contains a div element with id id, which contains a series of images (img nodes). Write a function that takes two arguments, id and interval. At each interval, the images must be “rotated”, i.e., image0 will become image1, image1 will become image2, etc. DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Solution 17 1 function changeImages ( id , i n t e r v a l ) { 2 // Select the parent div by its id 3 c o n s t p a r e n t D i v = document. g e t E l e m e n t B y I d ( i d ) ; 4 i f ( ! p a r e n t D i v ) r e t u r n ; // Exit if the div is not found 5 6 // Function to perform the rotation of images 7 function rotateImages () { 8 c o n s t i m a g e s = p a r e n t D i v. getElementsByTagName ( ’ img ’ ) ; 9 i f ( images. l e n g t h > 0) { 10 // Remove the first image and add it to the end 11 parentDiv. appendChild ( images [ 0 ] ) ; 12 } 13 } 14 15 // Set up the interval to rotate images 16 s e t I n t e r v a l ( rotateImages , i n t e r v a l ) ; 17 } DOM: Recap Selecting DOM elements DOM Traversal Modifying DOM Elements Adding and removing nodes Table of Contents 42 1 DOM: Recap 2 Selecting DOM elements 3 DOM Traversal 4 Modifying DOM Elements 5 Adding and removing nodes