JavaScript

Last Updated: 2/3/2023

Document Object Model

  • DOM defines a standard for accessing documents.
  • DOM is a W3C (World Wide Web Consortium) standard.
  • Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.
  • DOM standard is separated into 3 different parts:
    • Core DOM - standard model for all document types
    • XML DOM - standard model for XML documents
    • HTML DOM - standard model for HTML documents

HTML DOM

  • HTML DOM is a standard object model and programming interface for HTML. It defines HTML elements as objects.
  • Each object exposes properties, methods and events
  • When a web page is loaded, the browser creates a Document Object Model of the page.
  • The HTML DOM model is constructed as a tree of Objects

Document Object

  • Document object is the owner of all other objects in your web page.
  • Document object represents your web page.
  • document.body - The body of the document <body
  • document.documentElement - The full document <html>

Finding HTML Elements

  • document.getElementById(id): Find an element by element id
  • document.getElementsByTagName(name): Find elements by tag name
  • document.getElementsByClassName(name): Find elements by class name

By Id

If the element is found, the method will return the element as an object (in element). If the element is not found, element will contain null. document.getElementById("div1");

By TagName

document.getElementsByTagName("p");

By ClassName

document.getElementsByClassName("btn");

By CSS Selector

document.querySelectorAll("ul.list");

By Collections

  • document.forms
  • document.images
  • document.links
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length; i++) {
  text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;

Changing HTML Elements

Properties

  • element.innerHTML: Get or set the inner HTML of an element
  • element.attribute: Get or set the attribute value of an HTML element
  • element.style.property: Get or set the style of an HTML element
document.getElementById("p1").innerHTML = "New content";
document.getElementById("img1").src = "flower.jpg";
document.getElementById("p2").style.color = "blue";

Methods

  • element.setAttribute - Change the attribute value of an HTML element

Events

  • A JavaScript can be executed when an event occurs,

Using Event Attributes

<button onclick="displayDate()">Try it</button>

Using the HTML DOM

<script>
document.getElementById("button1").onclick = displayDate;
</script>

Using Event Listener

  • Attaches an event handler to an element without overwriting existing event handlers.
  • You can assign multiple handlers to one event.
document.getElementById("button1").addEventListener("click", displayDate);
document.getElementById("button1").removeEventListener("click", displayDate);

Event Propagation

  • There are two ways of event propagation in the HTML DOM, bubbling and capturing.
  • In bubbling the inner most element's event is handled first and then the outer
  • In capturing the outer most element's event is handled first and then the inner

Form Validation

HTML

<form name="myForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

JS

function validateForm() {
  let x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}

DOM Navigation

  • You can navigate the node tree using node relationships.
  • A node is the generic name for any type of object in the DOM hierarchy.

DOM Nodes

According to the W3C HTML DOM standard, everything in an HTML document is a node:

  • The entire document is a document node
  • Every HTML element is an element node
  • The text inside HTML elements are text nodes
  • Every HTML attribute is an attribute node (deprecated)
  • All comments are comment nodes
  • You can use the following node properties to navigate between nodes with JavaScript:
    • parentNode
    • childNodes[nodenumber]
    • firstChild
    • lastChild
    • nextSibling
    • previousSibling
document.getElementById("div1").innerHTML;
document.getElementById("div1").firstChild.nodeValue;
document.getElementById("div1").childNodes[0].nodeValue;

nodeName Property

  • The nodeName property specifies the name of a node.
  • nodeName is read-only
  • nodeName of an element node is the same as the tag name
  • nodeName of an attribute node is the attribute name
  • nodeName of a text node is always #text
  • nodeName of the document node is always #document
  • nodeName always contains the uppercase tag name of an HTML element.

nodeValue Property

  • The nodeValue property specifies the value of a node.
  • nodeValue for element nodes is null
  • nodeValue for text nodes is the text itself
  • nodeValue for attribute nodes is the attribute value

nodeType Property

  • The nodeType property is read only. It returns the type of a node.

Adding and Deleting Elements

  • document.createElement(element): Create an HTML element
  • document.getElementById("p1").remove: Remove an element
  • document.appendChild(element): Add an element as the last child of the parent.
  • insertBefore: Insert before a child element
  • document.replaceChild(new, old): Replace an child element
  • document.removeChild(element): Remove an child element

Creating Element

const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);

const element = document.getElementById("div1");
element.appendChild(para);

HTMLCollection

  • getElementsByTagName() method returns an HTMLCollection object.
  • An HTMLCollection object is an collection of HTML elements similar to array but not array
  • The elements in the collection can be accessed by an index number.
  • The length property defines the number of elements in an HTMLCollection
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
  myCollection[i].style.color = "red";
}

NodeList

  • A NodeList object is a list (collection) of nodes extracted from a document.
  • A NodeList object is almost the same as an HTMLCollection object.
  • Some (older) browsers return a NodeList object instead of an HTMLCollection for methods like getElementsByClassName().
  • All browsers return a NodeList object for the property childNodes.
  • Most browsers return a NodeList object for the method querySelectorAll().
const myNodelist = document.querySelectorAll("p");
for (let i = 0; i < myNodelist.length; i++) {
  conosle.log(myNodelist[i].style.color);
}

References

https://www.w3schools.com/jsref/dom_obj_style.asp https://www.w3schools.com/jsref/dom_obj_event.asp