Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com JavaScript DOM Document Object Model – DOM >> A Web page is a document. This document can be either displayed in the browser window or as the HTML source. But it is the same document in both cases. The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript. The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content. <html> <head> <title>My Document</title> </head> <body> <h1>Header</h1> <p>Paragraph</p> </body> </html> DOM Tree Document Interface >> The Document interface represents any web page loaded in the browser and serves as an entry point into the web page’s content, which is the DOM tree. Properties: Property Name document.head - returns the <head> element of the current document (read-only) document.body - returns the <body> node of the current document document.forms - returns a list of <form> elements within the current document (read-only) document.URL - returns the document location as a string (read-only) document.cookie - returns a semicolon-separated list of the cookies for that document or, sets a single cookie
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com Methods: Method Name Sample Code document.createElement (tagname_string) - creates a new HTML element with the given tag name <!DOCTYPE html> <html> <head> <title>||Working with elements||</title> </head> <body> <div id="div1">The text above has been created dynamically.</div> <script> document.body.onload = addElement; function addElement () { // create a new div element var newDiv = document.createElement("div"); // and give it some content var newContent = document.createTextNode("Hi there and greetings!"); // add the text node to the newly created div newDiv.appendChild(newContent); // add the newly created element and its content into the DOM var currentDiv = document.getElementById("div1"); document.body.insertBefore(newDiv, currentDiv); } </script> </body> </html> document.createTextNode (text_string) - creates a new Text node - this method can be used to escape HTML characters <!DOCTYPE html> <html lang="en"> <head> <title>createTextNode example</title> <script> function addTextNode(text) { var newtext = document.createTextNode(text), p1 = document.getElementById("p1"); p1.appendChild(newtext); } </script> </head> <body> <button onclick="addTextNode('YES! ');">YES!</button> <button onclick="addTextNode('NO! ');">NO!</button> <button onclick="addTextNode('WE CAN! ');">WE CAN!</button> <hr /> <p id="p1">First line of paragraph.</p> </body> </html>
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com document.getElementsByClassName (classname_string) - returns a list of all elements with the given class name document.getElementsByTagName (tagname_string) - returns a list of elements with the given tag name document.getElementsByName (name_value) - returns a list of elements where the name attribute contains the value name_value document.getElementById (id_string) - returns an Element object representing the element whose id property matches the specified id_string. <html> <head> <title>getElementById example</title> </head> <body> <p id="para">Some text here</p> <button onclick="changeColor('blue');">blue</button> <button onclick="changeColor('red');">red</button> <script> function changeColor(newColor) { var elem = document.getElementById('para'); elem.style.color = newColor; } </script> </body> </html> document.querySelectorAll (selector_string) - returns a list of the document’s elements that match the specified group of selectors. <!DOCTYPE html> <html> <body> <p>Hello World!</p> <p class="intro">The DOM is very useful.</p> <p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p> <p id="demo"></p> <script> var x = document.querySelectorAll("p.intro"); document.getElementById("demo").innerHTML = 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML; </script> </body> </html>
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com document.querySelector (selector_string) - matches the specified selector and returns the first element - for no matches, returns null. document.open() - opens a document for writing (side effect all existing nodes are removed from the document) document.write(string) - writes a string of text to document document.close() - finishes writing to a document document.open(); document.write("<p>Hello world!</p>"); document.write("<p>I am a fish</p>"); document.write("<p>The number is 42</p>"); document.close(); Element Interface >> Properties: Property Name Sample Code element.innerHTML - gets / sets the HTML contained within the element element.outerHTML - gets / sets this node with another node <html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "New text!"; </script> </body> </html> element.attributeName - gets/sets the attribute values <!DOCTYPE html> <html> <body> <img id="myImage" src="smiley.gif"> <script> document.getElementById("myImage").src = "landscape.jpg"; </script> </body> </html> element.classList - returns a collection object of the class attributes of the element - Methods: add(class1, class2, … ), remove(class1, class2, … ), toggle(class1), contains(class1), replace(‘current_class’,’replaced_class’) const div = document.createElement('div'); div.className = 'foo'; // our starting state: <div class="foo"></div> console.log(div.outerHTML); // use the classList API to remove and add classes div.classList.remove("foo"); div.classList.add("anotherclass");
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com // <div class="anotherclass"></div> console.log(div.outerHTML); // if visible is set remove it, otherwise add it div.classList.toggle("visible"); console.log(div.classList.contains("foo")); // add or remove multiple classes div.classList.add("foo", "bar", "baz"); div.classList.remove("foo", "bar", "baz"); // replace class "foo" with class "bar" div.classList.replace("foo", "bar"); element.scrollTop - gets or sets the number of pixels that an element’s content is scrolled vertically element.scrollHeight - read-only property measuring the height of an element’s content, including content not visible on the screen due to overflow. element.scrollWidth - read-only property measuring the width of an element’s content, including content not visible on the screen due to overflow. element.tagName - returns a string with the name of the tag for the given element HTMLelement.style - to get and set the inline style of an element. - returns a CSSStyleDeclaration object that contains a list of all style properties. Methods: setProperty(prop_name, value), getPropertyValue(prop_name), removeProperty(prop_name) // Set multiple styles in a single statement elt.style.cssText = "color: blue; border: 1px solid black"; // Or elt.setAttribute("style", "color:red; border: 1px solid blue;"); // Set specific style while leaving other inline style values untouched elt.style.color = "blue"; Methods: Method Name Sample Code element.addEventListener(type, listenerfn) - registers an event handler element.removeEventListener(type, listenerfn) - removes an event handler from the element
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com element.setAttribute(attr_name, value) - sets value of an attribute on the specified element. If the attribute doesn’t exists then a new attribute is added with the specified name and value. - to set Boolean attribute value to true, set the value to empty string “” and to set the Boolean attribute value to false, just remove this Boolean attribute. element.removeAttribute(attr_name) - removes the attribute with the specified value from the element. element.hasAttribute(attr_name) - returns true/false indicating whether the specified element has the specified attribute or not. element.getAttribute(attr_name) - returns the value of a specified attribute on the element. element.toggleAttribute(attr_name) - toggles a Boolean attribute, removing it if it is present and adding it if it is not present on the specified element. <button>Hello World</button> <script> var b = document.querySelector("button"); b.setAttribute("name", "helloButton"); b.setAttribute("disabled", ""); </script> Node Interface >> Properties: Property Name Sample Code node.parentNode - returns the parent of the specified node in the DOM tree if (node.parentNode) { // remove a node from the tree, unless // it's not in the tree already node.parentNode.removeChild(node); } node.childNodes - returns a NodeList of all the child nodes of the given element, first child index is 0 var children = parg.childNodes; for (var i = 0; i < children.length; i++) { // do something with each child as children[i] // NOTE: List is live, adding or removing children will change the list } node.nextSibling - returns a Node representing the next node in the tree or null. node.previousSibling - returns a Node representing the previous node in the tree or null.
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com node.textContent - returns the text content of the node and its descendants Methods: Method Name Sample Code node.appendChild(childobject) - adds a node to the end of the list of children of a specified parent node. node.removeChild(childobject) - removes a child node from the DOM and returns the removed node. node.replaceChild(newchild, oldchild) - replaces one child node of the current one with the second one given in parameter // Create a new paragraph element, and append it to the end of the document body var p = document.createElement("p"); document.body.appendChild(p); // To remove a node <div id="top"> <div id="nested"></div> </div> <script> let node= document.getElementById("nested"); if (node.parentNode) { node.parentNode.removeChild(node); } </script> node.insertBefore(newnode, referencenode) - inserts a newnode before a referencenode as a child of the specified node. Location Interface >> Method Name Sample Code location.assign() -- loads the resource at the URL provided in parameter document.location.assign('https://developer.mozilla.org/en- US/docs/Web/API/Location/assign’); location.reload() -- reloads the resource from the current URL // Reload the current page without the browser cache location.reload(true); Window Interface >> Properties: Property Name Sample Code window.console - returns a reference to the browser’s debugging console console.log(‘log value’); window.document - returns a reference to the document that the window content
Mohammad Imam Hossain, Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com window.location - returns a Location object with information about the current location of the document. window.event - returns the current event which is the event currently being handled by the JavaScript code’s context or undefined. window.navigator - returns a reference to the Navigator object. window.history - returns a reference to the History object window.screen -- returns a reference to the Screen object Methods: Method Name Sample Code window.alert(alert_msg_string) - displays an alert dialog window.confirm(confirmation_string) - displays a dialog with a message that the user needs to respond to. Returns either true or false window.prompt(alert_msg_string) - returns the text entered by the user in a prompt dialog or null. window.print(print_string) - opens the print dialog to print the current document References >> 1. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs 2. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction 3. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents 4. https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction 5. https://www.w3schools.com/js/

Web 6 | JavaScript DOM

  • 1.
    Mohammad Imam Hossain,Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com JavaScript DOM Document Object Model – DOM >> A Web page is a document. This document can be either displayed in the browser window or as the HTML source. But it is the same document in both cases. The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript. The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content. <html> <head> <title>My Document</title> </head> <body> <h1>Header</h1> <p>Paragraph</p> </body> </html> DOM Tree Document Interface >> The Document interface represents any web page loaded in the browser and serves as an entry point into the web page’s content, which is the DOM tree. Properties: Property Name document.head - returns the <head> element of the current document (read-only) document.body - returns the <body> node of the current document document.forms - returns a list of <form> elements within the current document (read-only) document.URL - returns the document location as a string (read-only) document.cookie - returns a semicolon-separated list of the cookies for that document or, sets a single cookie
  • 2.
    Mohammad Imam Hossain,Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com Methods: Method Name Sample Code document.createElement (tagname_string) - creates a new HTML element with the given tag name <!DOCTYPE html> <html> <head> <title>||Working with elements||</title> </head> <body> <div id="div1">The text above has been created dynamically.</div> <script> document.body.onload = addElement; function addElement () { // create a new div element var newDiv = document.createElement("div"); // and give it some content var newContent = document.createTextNode("Hi there and greetings!"); // add the text node to the newly created div newDiv.appendChild(newContent); // add the newly created element and its content into the DOM var currentDiv = document.getElementById("div1"); document.body.insertBefore(newDiv, currentDiv); } </script> </body> </html> document.createTextNode (text_string) - creates a new Text node - this method can be used to escape HTML characters <!DOCTYPE html> <html lang="en"> <head> <title>createTextNode example</title> <script> function addTextNode(text) { var newtext = document.createTextNode(text), p1 = document.getElementById("p1"); p1.appendChild(newtext); } </script> </head> <body> <button onclick="addTextNode('YES! ');">YES!</button> <button onclick="addTextNode('NO! ');">NO!</button> <button onclick="addTextNode('WE CAN! ');">WE CAN!</button> <hr /> <p id="p1">First line of paragraph.</p> </body> </html>
  • 3.
    Mohammad Imam Hossain,Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com document.getElementsByClassName (classname_string) - returns a list of all elements with the given class name document.getElementsByTagName (tagname_string) - returns a list of elements with the given tag name document.getElementsByName (name_value) - returns a list of elements where the name attribute contains the value name_value document.getElementById (id_string) - returns an Element object representing the element whose id property matches the specified id_string. <html> <head> <title>getElementById example</title> </head> <body> <p id="para">Some text here</p> <button onclick="changeColor('blue');">blue</button> <button onclick="changeColor('red');">red</button> <script> function changeColor(newColor) { var elem = document.getElementById('para'); elem.style.color = newColor; } </script> </body> </html> document.querySelectorAll (selector_string) - returns a list of the document’s elements that match the specified group of selectors. <!DOCTYPE html> <html> <body> <p>Hello World!</p> <p class="intro">The DOM is very useful.</p> <p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p> <p id="demo"></p> <script> var x = document.querySelectorAll("p.intro"); document.getElementById("demo").innerHTML = 'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML; </script> </body> </html>
  • 4.
    Mohammad Imam Hossain,Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com document.querySelector (selector_string) - matches the specified selector and returns the first element - for no matches, returns null. document.open() - opens a document for writing (side effect all existing nodes are removed from the document) document.write(string) - writes a string of text to document document.close() - finishes writing to a document document.open(); document.write("<p>Hello world!</p>"); document.write("<p>I am a fish</p>"); document.write("<p>The number is 42</p>"); document.close(); Element Interface >> Properties: Property Name Sample Code element.innerHTML - gets / sets the HTML contained within the element element.outerHTML - gets / sets this node with another node <html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "New text!"; </script> </body> </html> element.attributeName - gets/sets the attribute values <!DOCTYPE html> <html> <body> <img id="myImage" src="smiley.gif"> <script> document.getElementById("myImage").src = "landscape.jpg"; </script> </body> </html> element.classList - returns a collection object of the class attributes of the element - Methods: add(class1, class2, … ), remove(class1, class2, … ), toggle(class1), contains(class1), replace(‘current_class’,’replaced_class’) const div = document.createElement('div'); div.className = 'foo'; // our starting state: <div class="foo"></div> console.log(div.outerHTML); // use the classList API to remove and add classes div.classList.remove("foo"); div.classList.add("anotherclass");
  • 5.
    Mohammad Imam Hossain,Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com // <div class="anotherclass"></div> console.log(div.outerHTML); // if visible is set remove it, otherwise add it div.classList.toggle("visible"); console.log(div.classList.contains("foo")); // add or remove multiple classes div.classList.add("foo", "bar", "baz"); div.classList.remove("foo", "bar", "baz"); // replace class "foo" with class "bar" div.classList.replace("foo", "bar"); element.scrollTop - gets or sets the number of pixels that an element’s content is scrolled vertically element.scrollHeight - read-only property measuring the height of an element’s content, including content not visible on the screen due to overflow. element.scrollWidth - read-only property measuring the width of an element’s content, including content not visible on the screen due to overflow. element.tagName - returns a string with the name of the tag for the given element HTMLelement.style - to get and set the inline style of an element. - returns a CSSStyleDeclaration object that contains a list of all style properties. Methods: setProperty(prop_name, value), getPropertyValue(prop_name), removeProperty(prop_name) // Set multiple styles in a single statement elt.style.cssText = "color: blue; border: 1px solid black"; // Or elt.setAttribute("style", "color:red; border: 1px solid blue;"); // Set specific style while leaving other inline style values untouched elt.style.color = "blue"; Methods: Method Name Sample Code element.addEventListener(type, listenerfn) - registers an event handler element.removeEventListener(type, listenerfn) - removes an event handler from the element
  • 6.
    Mohammad Imam Hossain,Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com element.setAttribute(attr_name, value) - sets value of an attribute on the specified element. If the attribute doesn’t exists then a new attribute is added with the specified name and value. - to set Boolean attribute value to true, set the value to empty string “” and to set the Boolean attribute value to false, just remove this Boolean attribute. element.removeAttribute(attr_name) - removes the attribute with the specified value from the element. element.hasAttribute(attr_name) - returns true/false indicating whether the specified element has the specified attribute or not. element.getAttribute(attr_name) - returns the value of a specified attribute on the element. element.toggleAttribute(attr_name) - toggles a Boolean attribute, removing it if it is present and adding it if it is not present on the specified element. <button>Hello World</button> <script> var b = document.querySelector("button"); b.setAttribute("name", "helloButton"); b.setAttribute("disabled", ""); </script> Node Interface >> Properties: Property Name Sample Code node.parentNode - returns the parent of the specified node in the DOM tree if (node.parentNode) { // remove a node from the tree, unless // it's not in the tree already node.parentNode.removeChild(node); } node.childNodes - returns a NodeList of all the child nodes of the given element, first child index is 0 var children = parg.childNodes; for (var i = 0; i < children.length; i++) { // do something with each child as children[i] // NOTE: List is live, adding or removing children will change the list } node.nextSibling - returns a Node representing the next node in the tree or null. node.previousSibling - returns a Node representing the previous node in the tree or null.
  • 7.
    Mohammad Imam Hossain,Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com node.textContent - returns the text content of the node and its descendants Methods: Method Name Sample Code node.appendChild(childobject) - adds a node to the end of the list of children of a specified parent node. node.removeChild(childobject) - removes a child node from the DOM and returns the removed node. node.replaceChild(newchild, oldchild) - replaces one child node of the current one with the second one given in parameter // Create a new paragraph element, and append it to the end of the document body var p = document.createElement("p"); document.body.appendChild(p); // To remove a node <div id="top"> <div id="nested"></div> </div> <script> let node= document.getElementById("nested"); if (node.parentNode) { node.parentNode.removeChild(node); } </script> node.insertBefore(newnode, referencenode) - inserts a newnode before a referencenode as a child of the specified node. Location Interface >> Method Name Sample Code location.assign() -- loads the resource at the URL provided in parameter document.location.assign('https://developer.mozilla.org/en- US/docs/Web/API/Location/assign’); location.reload() -- reloads the resource from the current URL // Reload the current page without the browser cache location.reload(true); Window Interface >> Properties: Property Name Sample Code window.console - returns a reference to the browser’s debugging console console.log(‘log value’); window.document - returns a reference to the document that the window content
  • 8.
    Mohammad Imam Hossain,Lecturer, Dept. of CSE, UIU. Email: imambuet11@gmail.com window.location - returns a Location object with information about the current location of the document. window.event - returns the current event which is the event currently being handled by the JavaScript code’s context or undefined. window.navigator - returns a reference to the Navigator object. window.history - returns a reference to the History object window.screen -- returns a reference to the Screen object Methods: Method Name Sample Code window.alert(alert_msg_string) - displays an alert dialog window.confirm(confirmation_string) - displays a dialog with a message that the user needs to respond to. Returns either true or false window.prompt(alert_msg_string) - returns the text entered by the user in a prompt dialog or null. window.print(print_string) - opens the print dialog to print the current document References >> 1. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs 2. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction 3. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents 4. https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction 5. https://www.w3schools.com/js/