JavaScript and the HTML DOM (Document Object Model)
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.
The DOM is a W3C (World Wide Web Consortium) standard. It defines a standard for accessing documents:
The W3C 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.
With the object model, JavaScript gets all the power it needs to create dynamic HTML. JavaScript can:
- change all and any of the HTML elements or its attributes in the page
- modify all the CSS styles in the page
- remove existing HTML elements and attributes, or add new ones
- react to all existing HTML events in the page
- create new HTML events in the page
The Basics: ...
The most common way to access an HTML element is to use the id of the element by means of the document's getElementById(ID)
methods.
And the easiest way to get the content of an element is by using the innerHTML
property. The innerHTML
property is useful for getting or replacing the content of HTML elements.
Last, the HTML DOM document object (document
) is the owner of all other objects in your web page.
The following example applies all three components (document
, getElementById(ID)
, and innerHTML
) to change the content (the innerHTML) of the <p> element with id="demo":
<html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html>
In the example above, getElementById(ID)
is a method, while innerHTML
is a property.
Some Common Methods and Variables for Accessing the DOM
Finding HTML Elements
Method | Description |
document.getElementById(id) | Find an element by element id |
document.getElementsByTagName(name) | Find elements by tag name: returns an HTMLCollection object, which is an array-like list (collection) of HTML elements |
document.getElementsByClassName(name) | Find elements by class name |
Changing HTML Elements
Property/Method | Description |
element.innerHTML = new_html_content | Change the inner HTML of an element |
element.attribute = new_value | Change the attribute value of an HTML element |
element.style.property = new_style | Change the style of an HTML element |
element.setAttribute(attribute, value) | Change the attribute value of an HTML element |
Adding and Deleting Elements
Method | Description |
document.createElement(element) | Create an HTML element |
document.removeChild(element) | Remove an HTML element |
document.appendChild(element) | Add an HTML element |
document.replaceChild(new, old) | Replace an HTML element |
document.write(text) | Write into the HTML output stream |
Adding Events Handlers
Method | Description |
document.getElementById(id).onclick = function() {code} | Adding event handler code to an onclick event |
document.getElementsByClassName(className) | get all elements with the same class name |
document.querySelectorAll(querySelector) | find all HTML elements that match a specified CSS selector |
Finding HTML Objects
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5. Later, in HTML DOM Level 3, more objects, collections, and properties were added.
Method | Description | DOM |
document.anchors | Deprecated. Do not use it | 1 |
document.applets | Deprecated. Do not use it | 1 |
document.baseURI | Returns the absolute base URI of the document | 3 |
document.body | Returns the <body> element | 1 |
document.cookie | Returns the document's cookie | 1 |
document.doctype | Returns the document's doctype | 3 |
document.documentElement | Returns the <html> element | 3 |
document.documentMode | Returns the mode used by the browser | 3 |
document.documentURI | Returns the URI of the document | 3 |
document.domain | Deprecated. Do not use it | 1 |
document.domConfig | Deprecated. Do not use it | 3 |
document.embeds | Returns all <embed> elements | 3 |
document.forms | Returns all <form> elements | 1 |
document.head | Returns the <head> element | 3 |
document.images | Returns all <img> elements | 1 |
document.implementation | Returns the DOM implementation | 3 |
document.inputEncoding | Returns the document's encoding (character set) | 3 |
document.lastModified | Returns the date and time the document was updated | 3 |
document.links | Returns all <area> and <a> elements that have a href attribute | 1 |
document.readyState | Returns the (loading) status of the document | 3 |
document.referrer | Returns the URI of the referrer (the linking document) | 1 |
document.scripts | Returns all <script> elements | 3 |
document.strictErrorChecking | Returns if error checking is enforced | 3 |
document.title | Returns the <title> element | 1 |
document.URL | Returns the complete URL of the document | 1 |
Properties innerHTML
, value
, innerText
, innerContent
*
The innerHTML
property sets or returns the HTML content (inner HTML) of an element.
let text = "Hello Dolly."; document.getElementById("myP").innerHTML = text;
The innerText
property returns just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.
The textContent
property returns the text content of the element and all descendants, with spacing and CSS hidden text, but without tags.
HTML Example
<p id="myP"> This element has extra spacing and contains <span>a span element</span>.</p>
JavaScript Examples:
let text = document.getElementById("myP").innerText; let text = document.getElementById("myP").innerHTML; let text = document.getElementById("demo").textContent;
value
is a property specifically for form elements like <input>, <select>, and <textarea>. It returns the user's value entered or selected in a form field.
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML
property. To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML = newHTML
To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute = newValue
Dynamic HTML content
JavaScript can create dynamic HTML content:
Example
<!DOCTYPE html> <html> <body> <script> document.getElementById("demo").innerHTML = "Date : " + Date();</script> </body> </html>
document.write(TEXT)
In JavaScript, document.write()
can be used to write directly to the HTML output stream:
Example
<!DOCTYPE html> <html> <body> <p>Bla bla bla</p> <script> document.write(Date()); </script> <p>Bla bla bla</p> </body> </html>
Warning: Never use document.write()
after the document is loaded. It will overwrite the document.
JavaScript Forms
JavaScript Form Validation
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:
function validateForm() { let x = document.forms["myForm"]["fname"].value; if (x == "") { alert("Name must be filled out"); return false; } }
The function can be called when the form is submitted:
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"> <input type="submit" value="Submit"/> </form>
Automatic HTML Form Validation
HTML form validation can be performed automatically by the browser. If a form field (fname) is empty, the required attribute prevents this form from being submitted:
<form action="/action_page.php" method="post"> <input type="text" name="fname" required/> <input type="submit" value="Submit"/> </form>
HTML Constraint Validation
HTML5 introduced a new HTML validation concept called constraint validation. HTML constraint validation is based on:
- Constraint validation HTML Input Attributes
- Constraint validation CSS Pseudo Selectors
- Constraint validation DOM Properties and Methods
Constraint Validation HTML Input Attributes
Attribute | Description |
---|---|
disabled | Specifies that the input element should be disabled |
max | Specifies the maximum value of an input element |
min | Specifies the minimum value of an input element |
pattern | Specifies the value pattern of an input element |
required | Specifies that the input field requires an element |
type | Specifies the type of an input element |
For a full list, go to HTML Input Attributes
Constraint Validation CSS Pseudo Selectors
Selector | Description |
---|---|
:disabled | Selects input elements with the "disabled" attribute specified |
:invalid | Selects input elements with invalid values |
:optional | Selects input elements with no "required" attribute specified |
:required | Selects input elements with the "required" attribute specified |
:valid | Selects input elements with valid values |
For a full list, go to CSS Pseudo Classes
CSS*
(see https://www.w3schools.com/js/js_htmldom_css.asp)
The HTML DOM allows JavaScript to change the style of HTML elements. To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property = newStyle;
The following example changes the style of a <p> element:
<html> <body> <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color = "blue"; </script> </body> </html>
The following example changes the style of the HTML element with id="id1", when the user clicks a button:
<!DOCTYPE html> <html> <body> <h1 id="id1">My Heading 1</h1> <button type="button" onclick="document.getElementById('id1').style.color = 'red'"> Click Me!</button> </body> </html>
Animations*
JavaScript HTML DOM Events
HTML DOM allows JavaScript to react to HTML events. JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick="JavaScriptCode"
Examples of HTML events are triggered:
- When a user clicks the mouse
- When a web page has loaded
- When an image has been loaded
- When the mouse moves over an element
- When an input field is changed
- When an HTML form is submitted
- When a user strokes a key
In this example, the content of the <h1>
element is changed when a user clicks on it:
<!DOCTYPE html> <html> <body> <h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1> </body> </html>
In this example, a function is called from the event handler:
<!DOCTYPE html> <html> <body> <h1 onclick="changeText(this)">Click on this text!</h1> <script> function changeText(id) { id.innerHTML = "You did click inside this field!"; } </script> </body> </html>
HTML Event Attributes
To assign events to HTML elements you can use event attributes.
Assign an onclick event to a button element:
<button onclick="displayDate()">Try it</button>
In the example above, a function named displayDate() will be executed when the button is clicked.
Further, the HTML DOM allows you to assign events to HTML elements using JavaScript:
<script> //Assign an onclick event to a button element: document.getElementById("myBtn").onclick = displayDate; </script>
The onload
and onunload
Events
The onload
and onunload
events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onload and onunload events can be used to deal with cookies.
<body onload="checkCookies()">
The oninput
Event
The oninput
event is often to some action while the user input data.
Below is an example of how to use the oninput
to change the content of an input field.
<input type="text" id="fname" oninput="upperCase()"/>
The onchange
Event
The onchange
event is often used in combination with validation of input fields.
In the example below the upperCase()
function will be called when a user changes the content of an input field.
<input type="text" id="fname" onchange="upperCase()"/>
The onmouseover
, onmouseout
, onmousedown
, onmouseup
, and onclick
Events
The onmouseover
and onmouseout
events can be used to trigger a function when the user mouses over, or out of, an HTML element. The onmousedown
, onmouseup
, and onclick
events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown
event is triggered, then, when the mouse-button is released, the onmouseup
event is triggered, finally, when the mouse-click is completed, the onclick
event is triggered.
JavaScript HTML DOM EventListener
The addEventListener()
method
Add an event listener that fires when a user clicks a button:
document.getElementById("myBtn").addEventListener("click", displayDate);
The addEventListener()
method attaches an event handler to the specified element. It does not overwrite already existing event handlers. Thus, you can add many event handlers to one element. You can even add several event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener()
method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener()
method.
Syntax
element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown" or any other HTML DOM Event.)
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.
In the following example alert("Hello World!")
is executed when the user clicks on an element:
element.addEventListener("click", function(){ alert("Hello World!"); });
You can also refer to an external "named" function:
element.addEventListener("click", myFunction); function myFunction() { alert ("Hello World!"); }
Add an Event Handler to the window Object
The addEventListener()
method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest
object.
Add an event listener that fires when a user resizes the window:
window.addEventListener("resize", function() { document.getElementById("demo").innerHTML = sometext; });
Event Bubbling or Event Capturing?
There are two ways of event propagation in the HTML DOM, bubbling and capturing. Event propagation is a way of defining the element order when an event occurs. If you have a <p>
element inside a <div>
element, and the user clicks on the <p>
element, which element's "click" event should be handled first?
In bubbling the innermost element's event is handled first and then the outer: the <p>
element's click event is handled first, then the <div>
element's click event.
In capturing the outermost element's event is handled first and then the inner: the <div>
element's click event will be handled first, then the <p>
element's click event.
With the addEventListener()
method you can specify the propagation type by using the >useCapture parameter (in effect the third element):
addEventListener(event, function, useCapture);
The default value is false
, which will use the bubbling propagation. When the value is set to true
, the event uses the capturing propagation.
Example
document.getElementById("myP").addEventListener("click", myFunction, true); document.getElementById("myDiv").addEventListener("click", myFunction, true);
The removeEventListener()
method
The removeEventListener()
method removes event handlers that have been attached with the addEventListener()
method:
element.removeEventListener("mousemove", myFunction);
JavaScript HTML DOM Elements (Nodes)
Creating New HTML Elements (Nodes)
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
Example
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> const para = document.createElement("p"); const node = document.createTextNode("This is new."); para.appendChild(node); const element = document.getElementById("div1"); element.appendChild(para); </script>
Creating new HTML Elements with insertBefore(node)
The appendChild()
method in the previous example appended the new element as the last child of the parent. If you don't want that you can use the insertBefore()
method:
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> const para = document.createElement("p"); const node = document.createTextNode("This is new."); para.appendChild(node); const element = document.getElementById("div1"); const child = document.getElementById("p1"); element.insertBefore(para, child); </script>
Removing Existing HTML Elements
To remove an HTML element, use the remove()
method:
<div> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> const elmnt = document.getElementById("p1"); elmnt.remove(); </script>
Replacing HTML Elements
To replace an element to the HTML DOM, use the replaceChild()
method:
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> const para = document.createElement("p"); const node = document.createTextNode("This is new."); para.appendChild(node); const parent = document.getElementById("div1"); const child = document.getElementById("p1"); parent.replaceChild(para, child); </script>
Browser BOM
There are no official standards for the Browser Object Model (BOM). Still, since modern browsers have implemented (almost) the same methods and properties for JavaScript interactivity, it is often referred to, as methods and properties of the BOM.
The Window Object
The window object is supported by all browsers. It represents the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object. Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");
Window Size
Two properties can be used to determine the size of the browser window. Both properties return the sizes in pixels:
window.innerHeight
: the inner height of the browser window (in pixels)window.innerWidth
: the inner width of the browser window (in pixels)
Example
let w = window.innerWidth; let h = window.innerHeight;
Other window methods
window.open()
: open a new windowwindow.close()
: close the current windowwindow.moveTo()
: move the current windowwindow.resizeTo()
: resize the current window
JavaScript Window History
The window.history
object contains the browsers history. This object can be written without the window prefix.
To protect the privacy of the users, there are limitations to how JavaScript can access this object.
Some methods:
history.back()
: same as clicking back in the browserhistory.forward()
: same as clicking forward in the browser