Dirk Harriman Banner Image


Notes Javascript - Built In Functions



DOM - Document Object Model

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

A web page is a document that can be either displayed in the browser window or as the HTML source. In both cases, it is the same document but the Document Object Model (DOM) representation allows it to be manipulated. As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript.

All of the properties, methods, and events available for manipulating and creating web pages are organized into objects. For example, the document object that represents the document itself, any table objects that implement the HTMLTableElement DOM interface for accessing HTML tables, and so forth, are all objects.

The DOM & Javascript

The DOM is not part of the JavaScript language, but is instead a Web API used to build websites. JavaScript can also be used in other contexts. For example, Node.js runs JavaScript programs on a computer, but provides a different set of APIs, and the DOM API is not a core part of the Node.js runtime.

DOM Constructor

The Document constructor creates a new Document object that is a web page loaded in the browser and serving as an entry point into the page's content.

new Document();


DOM Instance Properties


The activeElement read-only property of the Document interface returns the Element within the DOM that currently has focus.

<p>Select some text from one of the text areas below:</p> <form id="form01"> <textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40"> This is Text Area One. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui. </textarea> <textarea name="ta-example-two" id="ta-example-two" rows="7" cols="40"> This is Text Area Two. Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam. </textarea> </form> <p>Active element ID: <em id="output-element"></em></p> <p>Selected text: <em id="output-text"></em></p>

function onMouseUp(e) { const activeTextarea = document.activeElement; const selection = activeTextarea.value.substring( activeTextarea.selectionStart, activeTextarea.selectionEnd ); const outputElement = document.getElementById("output-element"); const outputText = document.getElementById("output-text"); outputElement.innerHTML = activeTextarea.id; outputText.innerHTML = selection; } const textarea1 = document.getElementById("ta-example-one"); const textarea2 = document.getElementById("ta-example-two"); textarea1.addEventListener("mouseup", onMouseUp, false); textarea2.addEventListener("mouseup", onMouseUp, false);

Select some text from one of the text areas below:

Active element ID:
Selected text:



The adoptedStyleSheets property of the Document interface is used for setting an array of constructed stylesheets to be used by the document.

Note: A constructed stylesheet is a stylesheet created programmatically using the CSSStyleSheet() constructor (as compared to one created by a user-agent when importing a stylesheet from a script, imported using <style> and @import, or linked to via <link>).

The same constructed stylesheets can also be shared with one or more ShadowRoot instances using the ShadowRoot.adoptedStyleSheets property. Changing an adopted stylesheet will affect all the objects that adopt it.

Stylesheets in the property are evaluated along with the document's other stylesheets using the CSS cascade algorithm. Where the resolution of rules considers stylesheet order, adoptedStyleSheets are assumed to be ordered after those in Document.styleSheets.

Only stylesheets created using the CSSStyleSheet() constructor within the context of the current Document may be adopted.


The value is an array of CSSStyleSheet() instances that must have been created using the CSSStyleSheet() constructor within the context of the same Document.

If the array needs to be modified, then a new array must be assigned (in-place mutations like push() will throw an exception). Note however that the CSSStyleSheet() instances themselves can be modified, and these changes will apply wherever the stylesheet is adopted.


NotAllowedError DOMException

One of the CSSStyleSheet instances in the array was not created using the CSSStyleSheet() constructor or was constructed in a different document than the current document, such as one in a frame.


The code below shows a stylesheet being constructed, and then CSSStyleSheet.replaceSync() is called to add a rule to the sheet. The stylesheet is then added to an array and assigned to the adoptedStyleSheets property.

// CREATE AN EMPTY "CONSTRUCTED" STYLESHEET const sheet = new CSSStyleSheet(); // APPLY A RULE TO THE SHEET sheet.replaceSync("a { color: red; }"); // APPLY THE STYLESHEET TO A DOCUMENT document.adoptedStyleSheets = [sheet];

We can append a new rule to the stylesheet using CSSStyleSheet.insertRule().

sheet.insertRule("* { background-color: blue; }"); // THE DOCUMENT WILL NOW HAVE BLUE BACKGROUND.

Append a New Stylesheet

To append a whole new stylesheet to the adoptedStyleSheets property we have to create and assign a new combined array.
This is demonstrated below using spread-syntax:

const extraSheet = new CSSStyleSheet(); sheet.replaceSync("p { color: green; }"); // COMBINE THE EXISTING SHEETS AND NEW ONE document.adoptedStyleSheets = [...document.adoptedStyleSheets, extraSheet];

Sharing a stylesheet with a shadow DOM

We can share a stylesheet to a shadow root in a similar way.

// CREATE AN ELEMENT IN THE DOCUMENT AND THEN CREATE A SHADOW ROOT: const node = document.createElement("div"); const shadow = node.attachShadow({ mode: "open" }); //ADOPT THE SAME SHEET INTO THE SHADOW DOM shadow.adoptedStyleSheets = [sheet];

Note on ShadowRoot

Note: the ShadowRoot interface of the Shadow DOM API is the root node of a DOM subtree that is rendered separately from a document's main DOM tree.

You can retrieve a reference to an element's shadow root using its Element.shadowRoot property, provided it was created using Element.attachShadow() with the mode option set to open.

The adoptedStyleSheets property of the ShadowRoot interface sets an array of constructed stylesheets to be used by the shadow DOM subtree.


function changeCss01() { // CREATE NEW STYLE SHEET const sheet = new CSSStyleSheet(); // APPLY A RULE TO THE SHEET sheet.replaceSync("h5 { color:#f00; }"); // APPLY THE STYLE SHEET TO THIS DOM document.adoptedStyleSheets = [sheet]; }

Change H5 To Red



The Document.body property represents the <body> or <frameset> node of the current document, or null if no such element exists.


One of the following:

// GIVEN THIS HTML: <body id="oldBodyElement"></body> alert(document.body.id); // "oldBodyElement" const aNewBodyElement = document.createElement("body"); aNewBodyElement.id = "newBodyElement"; document.body = aNewBodyElement; alert(document.body.id); // "newBodyElement"


document.body is the element that contains the content for the document. In documents with <body> contents, returns the <body> element, and in frameset documents, this returns the outermost <frameset> element.

Though the body property is settable, setting a new body on a document will effectively remove all the current children of the existing <body> element.



The Document.characterSet read-only property returns the character encoding of the document that it's currently rendered with.

Note: A "character set" and a "character encoding" are related, but different. Despite the name of this property, it returns the encoding.

Users can override the developer-specified encoding inside the Content-Type header or inline like <meta charset="utf-8">. This override is provided to fix incorrect developer-specified encodings that result in garbled text.

Note: The properties document.charset and document.inputEncoding are legacy aliases for document.characterSet. Do not use them any more.

<button onclick="console.log(document.characterSet);"> Log character encoding </button> <!-- displays document's character encoding in the dev console, such as "ISO-8859-1" or "UTF-8" -->



The document.childElementCount read-only property returns the number of child elements of the document.

document.children; // HTMLCollection, USUALLY CONTAINING AN <html> ELEMENT, THE DOCUMENT'S ONLY CHILD document.childElementCount; // 1

The Element.childElementCount read-only property returns the number of child elements of this element.

let sidebar = document.getElementById("sidebar"); if (sidebar.childElementCount > 0) { // DO SOMETHING }



The read-only children property returns a live HTMLCollection which contains all of the child elements of the document upon which it was called.

For HTML documents, this is usually only the root <html> element.

Use Element.children for child elements of specific HTML elements within the document.


An HTMLCollection which is a live, ordered collection of the DOM elements which are children of the current document. You can access the individual child nodes in the collection by using either the item() method on the collection, or by using JavaScript array-style notation.

If the document has no element children, then children is an empty list with a length of 0.

document.children; // HTMLCollection [<html>] // Usually only contains the root <html> element, the document's only direct child

const myElement = document.getElementById("foo"); for (const child of myElement.children) { console.log(child.tagName); }



The Document.compatMode read-only property indicates whether the document is rendered in Quirks mode or Standards mode.


An enumerated value that can be:

Note: All these modes are now standardized, so the older "standards" and "almost standards" names are nonsensical and no longer used in standards.

if (document.compatMode === "BackCompat") { // in Quirks mode }

Quirks Mode

In the old days of the web, pages were typically written in two versions: One for Netscape Navigator, and one for Microsoft Internet Explorer. When the web standards were made at W3C, browsers could not just start using them, as doing so would break most existing sites on the web. Browsers therefore introduced two modes to treat new standards compliant sites differently from old legacy sites.

There are now three modes used by the layout engines in web browsers: quirks mode, limited-quirks mode, and no-quirks mode. In quirks mode, layout emulates behavior in Navigator 4 and Internet Explorer 5. This is essential in order to support websites that were built before the widespread adoption of web standards. In no-quirks mode, the behavior is (hopefully) the desired behavior described by the modern HTML and CSS specifications. In limited-quirks mode, there are only a very small number of quirks implemented.

The limited-quirks and no-quirks modes used to be called "almost-standards" mode and "full standards" mode, respectively. These names have been changed as the behavior is now standardized.

How Do Browsers Determine Which Mode To Use?

For HTML documents, browsers use a DOCTYPE in the beginning of the document to decide whether to handle it in quirks mode or standards mode. To ensure that your page uses full standards mode, make sure that your page has a DOCTYPE like in this example:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Hello World!</title> </head> <body></body> </html>

The DOCTYPE shown in the example, <!DOCTYPE html>, is the simplest possible, and the one recommended by current HTML standards. Earlier versions of the HTML standard recommended other variants, but all existing browsers today will use full standards mode for this DOCTYPE, even the dated Internet Explorer 6. There are no valid reasons to use a more complicated DOCTYPE. If you do use another DOCTYPE, you may risk choosing one which triggers almost standards mode or quirks mode.

Make sure you put the DOCTYPE right at the beginning of your HTML document. Anything before the DOCTYPE, like a comment or an XML declaration will trigger quirks mode in Internet Explorer 9 and older.

The only purpose of <!DOCTYPE html> is to activate no-quirks mode. Older versions of HTML standard DOCTYPEs provided additional meaning, but no browser ever used the DOCTYPE for anything other than switching between render modes.



The Document.contentType read-only property returns the MIME type that the document is being rendered as. This may come from HTTP headers or other sources of MIME information, and might be affected by automatic type conversions performed by either the browser or extensions.

Note: This property is unaffected by <meta> elements.


contentType is a read-only property.



The Document property cookie lets you read and write cookies associated with the document. It serves as a getter and setter for the actual values of the cookies.

allCookies = document.cookie;

In the code above allCookies is a string containing a semicolon-separated list of all cookies (i.e. key=value pairs). Note that each key and value may be surrounded by whitespace (space and tab characters): in fact, RFC 6265 mandates a single space after each semicolon, but some user agents may not abide by this.

HTTP Cookie

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. The browser may store the cookie and send it back to the same server with later requests. Typically, an HTTP cookie is used to tell if two requests come from the same browser—keeping a user logged in, for example. It remembers stateful information for the stateless HTTP protocol.

Cookies are mainly used for three purposes:

Cookies were once used for general client-side storage. While this made sense when they were the only way to store data on the client, modern storage APIs are now recommended.

Cookies are sent with every request, so they can worsen performance (especially for mobile data connections).

Modern APIs for client storage are the Web Storage API (localStorage and sessionStorage) and IndexedDB.

Web Storage API

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

IndexedDB API

IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data. While Web Storage is useful for storing smaller amounts of data, it is less useful for storing larger amounts of structured data. IndexedDB provides a solution. This is the main landing page for MDN's IndexedDB coverage — here we provide links to the full API reference and usage guides, browser support details, and some explanation of key concepts.

Write a new cookie

document.cookie = newCookie;

In the code above, newCookie is a string of form key=value, specifying the cookie to set/update. Note that you can only set/update a single cookie at a time using this method.
Consider also that:

Note: As you can see from the code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter.

$(document).ready(function(){ ... document.cookie = "name=oeschger; SameSite=None; Secure"; document.cookie = "favorite_food=tripe; SameSite=None; Secure"; }); function showCookies() { var divResult = document.getElementById("results1"); divResult.innerHTML = "document.cookie: "+ document.cookie; } function clearOutputCookies() { var divResult = document.getElementById("results1"); divResult.innerHTML = ""; }

Show Cookies Clear



$(document).ready(function(){ ... document.cookie = "test1=Hello; SameSite=None; Secure"; document.cookie = "test2=World; SameSite=None; Secure"; }); function showSpecificCookie() { var divResult = document.getElementById("results2"); const cookieValue = document.cookie .split("; ") .find((row) => row.startsWith("test2=")) ?.split("=")[1]; divResult.innerHTML = "cookieValue: "+ cookieValue; } function clearResult2() { var divResult = document.getElementById("results2"); divResult.innerHTML = ""; }

Show test2 Cookie Clear



function doSomethingOnlyOnce() { var divResult = document.getElementById("results3"); if ( !document.cookie .split("; ") .find((row) => row.startsWith("doSomethingOnlyOnce")) ) { document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; SameSite=None; Secure"; divResult.innerHTML = "document.cookie: "+ document.cookie; } }

Do Something Only Once Clear



function resetPreviousCookie() { var divResult = document.getElementById("results4"); document.cookie = "doSomethingOnlyOnce=; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=None; Secure"; divResult.innerHTML = "document.cookie: "+ document.cookie; }

Reset Previous Cookie Clear



function checkCookie() { var divResult = document.getElementById("results5"); if (document.cookie.split(";").some((item) => item.trim().startsWith("favorite_food="))) { divResult.innerHTML = "The cookie favorite_food exists"; } }

Check Cookie Clear



$(document).ready(function(){ ... document.cookie = "reader=1; SameSite=None; Secure"; }); function checkCookieValue() { var divResult = document.getElementById("results6"); if (document.cookie.split(";").some((item) => item.includes("reader=1"))) { divResult.innerHTML = "The cookie reader equals one"; } }

Check Cookie Clear




The Document.currentScript property returns the <script> element whose script is currently being processed and isn't a JavaScript module. (For modules use import.meta instead.)

It's important to note that this will not reference the <script> element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed.


A HTMLScriptElement or null.


if (document.currentScript.async) { console.log("Executing asynchronously"); } else { console.log("Executing synchronously"); }



In browsers, document.defaultView returns the window object associated with a document, or null if none is available.

This property is read-only.


The window object.



document.designMode controls whether the entire document is editable. Valid values are "on" and "off". According to the specification, this property is meant to default to "off".


A string indicating whether designMode is (or should be) set to on or off. Valid values are on and off.

// MAKE AN <iframe>'s DOCUMENT EDITABLE iframeNode.contentDocument.designMode = "on";



The Document.dir property is a string representing the directionality of the text of the document, whether left to right (default) or right to left. Possible values are rtl - right to left, and ltr - left to right.



A read-only property that returns the Document Type Declaration (DTD) associated with current document. The returned object implements the DocumentType interface. Use DOMImplementation.createDocumentType() to create a DocumentType.

Value A DocumentType object. Examples

const doctypeObj = document.doctype; console.log('doctypeObj.name: ${doctypeObj.name}'); console.log('doctypeObj.internalSubset: ${doctypeObj.internalSubset}'); console.log('doctypeObj.publicId: ${doctypeObj.publicId}'); console.log('doctypeObj.systemId: ${doctypeObj.systemId}');

Note: The property returns null if there is no DTD associated with the current document.



Document.documentElement returns the Element that is the root element of the document (for example, the <html> element for HTML documents).


An Element object.

Element Object

Element is the most general base class from which all element objects (i.e. objects that represent elements) in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element.

For example, the HTMLElement interface is the base interface for HTML elements, while the SVGElement interface is the basis for all SVG elements. Most functionality is specified further down the class hierarchy.

const rootElement = document.documentElement; const firstTier = rootElement.childNodes; // firstTier IS A NodeList OF THE DIRECT CHILDREN OF THE ROOT ELEMENT // SUCH AS <head> AND <body> for (const child of firstTier) { // DO SOMETHING WITH EACH DIRECT CHILD OF THE ROOT ELEMENT }

Note: For any non-empty HTML document, documentElement will always be an <html> element. For any non-empty XML document, documentElement will always be whatever element is the root element of the document.



The documentURI read-only property of the Document interface returns the document location as a string.

function getUrlString() { var divResult = document.getElementById("results7"); divResult.innerHTML = document.documentURI; }

Show URL





The document.embeds read-only property of the Document interface returns a list of the embedded <embed> elements within the current document.


An HTMLCollection.

The <embed> HTML element embeds external content at the specified point in the document. This content is provided by an external application or other source of interactive content such as a browser plug-in.

<embed type="video/webm" src="/media/cc0-videos/flower.mp4" width="250" height="200">



The Document.firstElementChild read-only property returns the document's first child Element, or null if there are no child elements.

For HTML documents, this is usually the only child, the root <html> element.


A Element object, or null.


The Element.firstElementChild read-only property returns an element's first child Element, or null if there are no child elements.

Element.firstElementChild includes only element nodes. To get all child nodes, including non-element nodes like text and comment nodes, use Node.firstChild.

<ul id="list"> <li>First (1)</li> <li>Second (2)</li> <li>Third (3)</li> </ul> <script> const list = document.getElementById("list"); console.log(list.firstElementChild.textContent); // logs "First (1)" </script>



The fonts property of the Document interface returns the FontFaceSet interface of the document.

This feature is part of the CSS Font Loading API.


The returned value is the FontFaceSet interface of the document. The FontFaceSet interface is useful for loading new fonts, checking the status of previously loaded fonts etc.




The forms read-only property of the Document interface returns an HTMLCollection listing all the <form> elements contained in the document.

Note: Similarly, you can access a list of a form's component user input elements using the HTMLFormElement.elements property.


An HTMLCollection object listing all of the document's forms. Each item in the collection is a HTMLFormElement representing a single <form> element.

Note: If the document has no forms, the returned collection is empty, with a length of zero.

<!DOCTYPE html> <html lang="en"> <head> <title>document.forms example</title> </head> <body> <form id="robby"> <input type="button" onclick="alert(document.forms[0].id);" value="robby's form" /> </form> <form id="dave"> <input type="button" onclick="alert(document.forms[1].id);" value="dave's form" /> </form> <form id="paul"> <input type="button" onclick="alert(document.forms[2].id);" value="paul's form" /> </form> </body> </html>

Getting An Element From Within A Form

const selectForm = document.forms[index]; const selectFormElement = document.forms[index].elements[index];

<!DOCTYPE html> <html lang="en"> <head> <title>document.forms example</title> </head> <body> <form name="login"> <input name="email" type="email" /> <input name="password" type="password" /> <button type="submit">Log in</button> </form> <script> const loginForm = document.forms.login; // Or document.forms['login'] loginForm.elements.email.placeholder = "test@example.com"; loginForm.elements.password.placeholder = "password"; </script> </body> </html>



The Document.fullscreenElement read-only property returns the Element that is currently being presented in fullscreen mode in this document, or null if fullscreen mode is not currently in use.

function isVideoInFullscreen() { if (document.fullscreenElement?.nodeName === "VIDEO") { return true; } return false; }



The read-only fullscreenEnabled property on the Document interface indicates whether or not fullscreen mode is available.

fullscreen mode is available only for a page that has no windowed plug-ins in any of its documents, and if all <iframe> elements which contain the document have their allowfullscreen attribute set.

In this example, before attempting to request fullscreen mode for a <video> element, the value of fullscreenEnabled is checked, in order to avoid making the attempt when not available.

function requestFullscreen() { if (document.fullscreenEnabled) { videoElement.requestFullscreen(); } else { console.log("Your browser cannot use fullscreen right now"); } }



The head read-only property of the Document interface returns the <head> element of the current document.

<!DOCTYPE html> <head id="my-document-head"> <title>Example: using document.head</title> </head> <script> const theHead = document.head; console.log(theHead.id); // "my-document-head"; console.log(theHead === document.querySelector("head")); // true </script>



The Document.hidden read-only property returns a Boolean value indicating if the page is considered hidden or not.

document.addEventListener("visibilitychange", () => { console.log(document.hidden); // MODIFY BEHAVIOR... });



The images read-only property of the Document interface returns a collection of the images in the current HTML document.


An HTMLCollection providing a live list of all of the images contained in the current document. Each entry in the collection is an HTMLImageElement representing a single image element.

Usage Notes

You can use either JavaScript array notation or the item() method on the returned collection to access the items in the collection. The following are equivalent:

firstImage = imageCollection.item(0); firstImage = imageCollection[0];

This example looks through the list of images and finds one whose name is "banner.gif".

for (const image of document.images) { if (image.src === "banner.gif") { console.log("Found the banner"); } }



The Document.implementation property returns a DOMImplementation object associated with the current document.

const modName = "HTML"; const modVer = "2.0"; const conformTest = document.implementation.hasFeature(modName, modVer); console.log('DOM ${modName} ${modVer} supported?: ${conformTest}'); // Log: "DOM HTML 2.0 supported?: true" if DOM Level 2 HTML module is supported.



The Document.lastElementChild read-only property returns the document's last child Element, or null if there are no child elements.

For HTML documents, this is usually the only child, the root <html> element.

See Element.lastElementChild for the last child element of specific elements within a document.

<ul id="list"> <li>First (1)</li> <li>Second (2)</li> <li>Third (3)</li> </ul> <script> const list = document.getElementById("list"); console.log(list.lastElementChild.textContent); // logs "Third (3)" </script>




































DOM Instance Methods
























































































DOM Events






























DOM Inheritance