Notes Javascript - Document Object Model


 

 
 

DOM - Document Object Model


The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory. Usually it refers to JavaScript, even though modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript language.

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.

Nodes can also have event handlers attached to them. Once an event is triggered, the event handlers get executed.

createElement()

In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized. The createElement(tagName) method can be used to create any HTML entity, such as <p>, <div>, <a>, etc... In this case we're creating a blank HTML page.

createElement(tagName) createElement(tagName, options)

Function Parameters
Parameter Description
tagName A string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don't use qualified names (like "html:a") with this method. When called on an HTML document, createElement() converts tagName to lower case before creating the element.
options An object with the following properties:
 
is
The tag name of a custom element previously defined via customElements.define().
 
See example below.

Returns: a new Element.

Loading A Remote HTML Doc Fragment

function runScript1(fileName) { var divResult = document.getElementById("results1"); let myPromise = new Promise(function(myResolve, myReject) { let req = new XMLHttpRequest(); req.open('GET', fileName); req.onload = function() { if (req.status == 200) { myResolve(req.response); } else { myReject("File not Found"); } }; req.send(); }); myPromise.then( function(value) {displayResult(divResult, value);}, function(error) {displayResult(error);} ); } function displayResult(divResult, resultTxt) { divResult.innerHTML = resultTxt; }

Run Script 1 
 

Response


 

 

 

Creating An HTML Page Dynamically

let el = document.createElement( 'html' );

In line 2 of the following code, we are assigning a string of HTML to the newly created blank web page.
In line 4 of the following code, we are creating a NodeList of all of the <table> elements in the HTML.

// ASSIGN A STRING OF HTML TO THE NEW BLANK PAGE el.innerHTML = someHtml; // GET A NODELIST OF ALL OF THE TABLES IN THE HTML let nodeList = el.getElementsByTagName("table");

getElementsByTagName() Return Value

A live HTMLCollection of elements with a matching tag name, in the order they appear. If no elements are found, the HTMLCollection is empty.

Note: an HTMLCollection and a NodeList are almost synonymous. A NodeList object is a list (collection) of nodes extracted from a document. 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().

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Notes Javascript</title> <meta charset="UTF-8"> <meta name="description" content="web developer"> <meta name="keywords" content="asp.net,c#,software,developer,javascript,jquery,css3,html5,mobile,web"> <meta name="author" content="Dirk Harriman"> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/png" href="favicon.png"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin=""> <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Azeret+Mono:wght@400;700&display=swap"> <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans"> <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Racing+Sans+One"> <link type="text/css" rel="stylesheet" href="../Styles/jquery-ui.min.css"> <link type="text/css" rel="stylesheet" href="../Styles/Site.css"> <script type="text/javascript" src="../Scripts/jquery.min.js"></script> <script type="text/javascript" src="../Scripts/jquery-ui.min.js"></script> </head> <body> <div class="container"> ... <h1>Simple HTML Page</h1> <br> <br> <table id="tblData01" class="def_table"> <caption>Data Table 01</caption> <thead> <tr> <th>Data Col 1</th> <th>Data Col 2</th> <th>Data Col 3</th> <th>Data Col 4</th> </tr> </thead> <tbody> <tr> <th>Type01</th> <td>123</td> <td>456</td> <td>789</td> </tr> ... </tbody> </table> <table id="tblData02" class="def_table"> <caption>Data Table 02</caption> <thead> <tr> <th>Data Col 1</th> <th>Data Col 2</th> <th>Data Col 3</th> <th>Data Col 4</th> </tr> </thead> <tbody> <tr> <th>Type01</th> <td>23</td> <td>56</td> <td>89</td> </tr> ... </tbody> </table> ... </body> </html>

If you click on the following button, it will open up a simple HTML file that will be used in the following code script.

simple_htm_page1.htm
 

The task is to read in and parse the html. The object to retrieve is the table with the id of tblData02

function runScript2(fileName) { var divResult = document.getElementById("results2"); let myPromise = new Promise(function(myResolve, myReject) { let req = new XMLHttpRequest(); req.open('GET', fileName); req.onload = function() { if (req.status == 200) { myResolve(req.response); } else { myReject("File not Found"); } }; req.send(); }); myPromise.then( function(value) {parseResult(divResult, value);}, function(error) {parseResult(error);} ); } function parseResult(divResult, resultTxt) { //let returnStr = resultTxt; let returnStr = ""; let el = document.createElement( 'html' ); // CREATES ELEMENT el.innerHTML = resultTxt; // ADD HTML TO ELEMENT // GET A NODELIST OF ALL OF THE TABLES IN THE HTML ELEMENT let nodeList = el.getElementsByTagName("table"); // DISPLAY THE NUMBER OF NODES FOUND returnStr = "nodeList.length: "+ nodeList.length; // LOOP THROUGH THE NODES for (const nodeCell of nodeList){ // CHECK FOR TABLE tblData02 if (nodeCell.getAttribute("id") == "tblData02") { returnStr += nodeCell.outerHTML; } } //returnStr += nodeList.item(0).outerHTML; divResult.innerHTML = returnStr; }

Run Script 2 
 

Response


 
Normal createElement() Process

This creates a new <div> and inserts it before the element with the ID "div1".

<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>Working with elements</title> </head> <body> <div id="div1">The text above has been created dynamically.</div> </body> </html>

// CREATE A NEW DIV ELEMENT const newDiv = document.createElement("div"); // AND GIVE IT SOME CONTENT const 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 const currentDiv = document.getElementById("div1"); document.body.insertBefore(newDiv, currentDiv);


 

Web Component Example

The following example snippet is taken from our expanding-list-web-component example. In this case, our custom element extends the HTMLUListElement, which represents the <ul> element.

// CREATE A CLASS FOR THE ELEMENT class ExpandingList extends HTMLUListElement { constructor() { // ALWAYS CALL super() FIRST IN CONSTRUCTOR super(); // CONSTRUCTOR DEFINITION LEFT OUT FOR BREVITY // ... } } // DEFINE THE NEW ELEMENT customElements.define("expanding-list", ExpandingList, { extends: "ul" });

If we wanted to create an instance of this element programmatically, we'd use a call along the following lines:

let expandingList = document.createElement("ul", { is: "expanding-list" });

The new element will be given an is attribute whose value is the custom element's tag name.


 
GitHub Example From Mozilla

See live example of the Expanded List.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Expanding list web component</title> <style> ul {list-style-type: none;} li::before {display:inline-block;width: 1rem;height: 1rem;margin-right: 0.25rem;content:"";} .open::before, .closed::before {background-size: 1rem 1rem;position: relative;top: 0.25rem;opacity: 0.3;} .open::before {background-image: url(img/down.png);} .closed::before {background-image: url(img/right.png);} .closed .closed::before, .closed .open::before {display: none;} </style> </head> <body> <h1>Expanding list web component</h1> <ul is="expanding-list"> <li>UK <ul> <li>Yorkshire <ul> <li>Leeds <ul> <li>Train station</li> <li>Town hall</li> <li>Headrow</li> </ul> </li> <li>Bradford</li> <li>Hull</li> </ul> </li> </ul> </li> <li>USA <ul> <li>California <ul> <li>Los Angeles</li> <li>San Francisco</li> <li>Berkeley</li> </ul> </li> <li>Nevada</li> <li>Oregon</li> </ul> </li> </ul> <ul> <li>Not</li> <li>an</li> <li>expanding</li> <li>list</li> </ul> <script src="main.js"></script> </body> </html>

// CREATE A CLASS FOR THE ELEMENT class ExpandingList extends HTMLUListElement { constructor() { // ALWAYS CALL super FIRST IN CONSTRUCTOR // RETURN VALUE FROM super() IS A REFERENCE TO THIS ELEMENT self = super(); // GET ul AND li ELEMENTS THAT ARE A CHILD OF THIS CUSTOM ul ELEMENT // li ELEMENTS CAN BE CONTAINERS IF THEY HAVE uls WITHIN THEM const uls = Array.from(self.querySelectorAll('ul')); const lis = Array.from(self.querySelectorAll('li')); // HIDE ALL CHILD uls // THESE LISTS WILL BE SHOWN WHEN THE USER CLICKS A HIGHER LEVEL CONTAINER uls.forEach(ul => { ul.style.display = 'none'; }); // LOOK THROUGH EACH li ELEMENT IN THE ul lis.forEach(li => { // IF THIS li HAS A ul AS A CHILD, DECORATE IT AND ADD A CLICK HANDLER if (li.querySelectorAll('ul').length > 0) { // ADD AN ATTRIBUTE WHICH CAN BE USED BY THE STYLE TO SHOW AN OPEN OR CLOSED ICON li.setAttribute('class', 'closed'); // WRAP THE li ELEMENT'S TEXT IN A NEW span ELEMENT SO WE CAN ASSIGN STYLE AND EVENT HANDLERS TO THE span const childText = li.childNodes[0]; const newSpan = document.createElement('span'); // COPY text FROM li TO span, SET CURSOR STYLE newSpan.textContent = childText.textContent; newSpan.style.cursor = 'pointer'; // ADD CLICK HANDLER TO THIS span newSpan.onclick = self.showul; // ADD THE span AND REMOVE THE BARE TEXT NODE FROM THE li childText.parentNode.insertBefore(newSpan, childText); childText.parentNode.removeChild(childText); } }); } // li CLICK HANDLER showul = function (e) { // NEXT SIBLING TO THE span SHOULD BE THE ul const nextul = e.target.nextElementSibling; // TOGGLE VISIBLE STATE AND UPDATE CLASS ATTRIBUTE ON ul if (nextul.style.display == 'block') { nextul.style.display = 'none'; nextul.parentNode.setAttribute('class', 'closed'); } else { nextul.style.display = 'block'; nextul.parentNode.setAttribute('class', 'open'); } }; } // DEFINE THE NEW ELEMENT customElements.define('expanding-list', ExpandingList, { extends: 'ul' });


 

append()

The Document.append() method inserts a set of Node objects or string objects after the last child of the document. String objects are inserted as equivalent Text nodes.

This method appends a child to a Document. To append to an arbitrary element in the tree, see Element.append().

append(param1) append(param1, param2) append(param1, param2, /* … ,*/ paramN)

Parameters
Parameter Description
param1, ..., paramN A set of Node or string objects to insert.
Returns
Return Value None (undefined).
Exceptions
HierarchyRequestError DOMException Thrown when the node cannot be inserted at the specified point in the hierarchy.

 

createAttribute()

The Document.createAttribute() method creates a new attribute node, and returns it. The object created is a node implementing the Attr interface. The DOM does not enforce what sort of attributes can be added to a particular element in this manner.

Note: The string given in parameter is converted to lowercase.

createAttribute(name)

Parameters
Parameter Description
name A string containing the name of the attribute.
Returns
Return Value A Attr node
Exceptions
InvalidCharacterError DOMException Thrown if the name value is not a valid XML name; for example, it starts with a number, hyphen, or period, or contains characters other than alphanumeric characters, underscores, hyphens, or periods.

const node = document.getElementById("div1"); const a = document.createAttribute("my_attrib"); a.value = "newVal"; node.setAttributeNode(a); console.log(node.getAttribute("my_attrib")); // "newVal"


 

createCDATASection()

createCDATASection() creates a new CDATA section node, and returns it.

createCDATASection(data)

Parameters
Parameter Description
data A string containing the data to be added to the CDATA Section.
Returns
Return Value A CDATA Section node.

const docu = new DOMParser().parseFromString("<xml></xml>", "application/xml"); const cdata = docu.createCDATASection("Some <CDATA> data & then some"); docu.querySelector("xml").appendChild(cdata); console.log(new XMLSerializer().serializeToString(docu)); // Displays: <xml><![CDATA[Some <CDATA> data & then some]]></xml>

Notes:
This will only work with XML, not HTML documents (as HTML documents do not support CDATA sections); attempting it on an HTML document will throw NOT_SUPPORTED_ERR.
 
Will throw a NS_ERROR_DOM_INVALID_CHARACTER_ERR exception if one tries to submit the closing CDATA sequence ("]]>") as part of the data, so unescaped user-provided data cannot be safely used without this method getting this exception (createTextNode() can often be used in its place).


 

createDocumentFragment()

Creates a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree.

createDocumentFragment()

Returns
Return Value A newly created, empty, DocumentFragment object, which is ready to have nodes inserted into it.
Usage Notes

DocumentFragments are DOM Node objects which are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children.

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Historically, using document fragments could result in better performance.

You can also use the DocumentFragment constructor to create a new fragment:

const fragment = new DocumentFragment();

Examples

This example creates a list of major web browsers in a DocumentFragment, then adds the new DOM subtree to the document to be displayed.

<ul id="ul"></ul>

const element = document.getElementById("ul"); // assuming ul exists const fragment = document.createDocumentFragment(); const browsers = ["Firefox", "Chrome", "Opera", "Safari"]; browsers.forEach((browser) => { const li = document.createElement("li"); li.textContent = browser; fragment.appendChild(li); }); element.appendChild(fragment);


 

getElementById()

The getElementById() method of the Document interface returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

If you need to get access to an element which doesn't have an ID, you can use querySelector() to find the element using any selector.

getElementById(id)


 

getElementByClassName()

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s).

Returns: a live HTMLCollection of found elements.

getElementsByClassName(names)


 

getElementByName()

The getElementsByName() method of the Document object returns a NodeList Collection of elements with a given name attribute in the document.

getElementByName(name)


 

getElementByTagName()

The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name.

The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.

getElementByTagName(name)


 

after()

The Element.after() method inserts a set of Node or string objects in the children list of the Element's parent, just after the Element. String objects are inserted as equivalent Text nodes.

after(node1) after(node1, node2) after(node1, node2, /* ... ,*/ nodeN)

Parameters
Parameter Description
node1,...,nodeN A set of Node or string objects to insert.
Returns
Return Value None (undefined).
Exceptions
HierarchyRequestError DOMException Thrown when the node cannot be inserted at the specified point in the hierarchy.

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.after(span); console.log(container.outerHTML); // "<div><p></p><span></span></div>"

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); p.after("Text"); console.log(container.outerHTML); // "<div><p></p>Text</div>"

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.after(span, "Text"); console.log(container.outerHTML); // "<div><p></p><span></span>Text</div>"


 

append()

The Element.append() method inserts a set of Node objects or string objects after the last child of the Element.
String objects are inserted as equivalent Text nodes.
 
Differences from Node.appendChild():

append(param1) append(param1, param2) append(param1, param2, /* ... ,*/ paramN)

Parameters
Parameter Description
param1,..., paramN A set of Node or string objects to insert.
Returns
Return Value None (undefined).
Exceptions
HierarchyRequestError DOMException Thrown when the node cannot be inserted at the specified point in the hierarchy.

let div = document.createElement("div"); let p = document.createElement("p"); div.append(p); console.log(div.childNodes); // NodeList [ <p> ]

let div = document.createElement("div"); div.append("Some text"); console.log(div.textContent); // "Some text"

let div = document.createElement("div"); let p = document.createElement("p"); div.append("Some text", p); console.log(div.childNodes); // NodeList [ #text "Some text", <p> ]

The append() method is not scoped into the with statement.

let div = document.createElement("div"); with (div) { append("foo"); } // ReferenceError: append is not defined


 

before()

The Element.before() method inserts a set of Node or string objects in the children list of this Element's parent, just before this Element.
String objects are inserted as equivalent Text nodes.

before(param1) before(param1, param2) before(param1, param2, /* ... ,*/ paramN)

Parameters
Parameter Description
param1,..., paramN A set of Node or string objects to insert.
Returns
Return Value None (undefined).
Exceptions
HierarchyRequestError DOMException Thrown when the node cannot be inserted at the specified point in the hierarchy.

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.before(span); console.log(container.outerHTML); // "<div><span></span><p></p></div>"

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); p.before("Text"); console.log(container.outerHTML); // "<div>Text<p></p></div>"

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.before(span, "Text"); console.log(container.outerHTML); // "<div><span></span>Text<p></p></div>"


 

getAttribute()

The getAttribute() method of the Element interface returns the value of a specified attribute on the element.

If the given attribute does not exist, the value returned will either be null or "" (the empty string);

getAttribute(attributeName)

Parameters
Parameter Description
attributeName The name of the attribute whose value you want to get.
Returns
Return Value A string containing the value of attributeName.

<!-- example div in an HTML DOC --> <div id="div1">Hi Champ!</div>

// IN A CONSOLE const div1 = document.getElementById("div1"); //=> <div id="div1">Hi Champ!</div> const exampleAttr = div1.getAttribute("id"); //=> "div1" const align = div1.getAttribute("align"); //=> null

Notes
Lower casing

When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.

Non-existing attributes

All modern web browsers return null when the specified attribute does not exist on the specified element.

Retrieving nonce values

For security reasons, CSP nonces from non-script sources, such as CSS selectors, and .getAttribute("nonce") calls are hidden.

let nonce = script.getAttribute("nonce"); // RETURNS EMPTY STRING

let nonce = script.nonce;


 

getAttributeNames()

The getAttributeNames() method of the Element interface returns the attribute names of the element as an Array of strings.
If the element has no attributes it returns an empty array.

Using getAttributeNames() along with getAttribute(), is a memory-efficient and performant alternative to accessing Element.attributes.

The names returned by getAttributeNames() are qualified attribute names, meaning that attributes with a namespace prefix have their names returned with that namespace prefix (not the actual namespace), followed by a colon, followed by the attribute name (for example, xlink:href), while any attributes which have no namespace prefix have their names returned as-is (for example, href).

getAttributeNames()

Returns
Return Value None (undefined).

The following example shows how:

It's important to understand that:

The example below includes such a "namespaced but without a namespace prefix" case.

const element = document.createElement("a"); // set "href" attribute with no namespace and no namespace prefix element.setAttribute("href", "https://example.com"); // set "href" attribute with namespace and also "xlink" namespace prefix element.setAttributeNS( "http://www.w3.org/1999/xlink", "xlink:href", "https://example.com" ); // set "show" attribute with namespace but no namespace prefix element.setAttributeNS("http://www.w3.org/1999/xlink", "show", "new"); // Iterate over element's attributes for (const name of element.getAttributeNames()) { const value = element.getAttribute(name); console.log(name, value); } // logs: // href https://example.com // xlink:href https://example.com // show new


 

getElementsByClassName()

The Element method getElementsByClassName() returns a live HTMLCollection which contains every descendant element which has the specified class name or names.

The method getElementsByClassName() on the Document interface works essentially the same way, except it acts on the entire document, starting at the document root.

getElementsByClassName(names)

Parameters
Parameter Description
names A string containing one or more class names to match on, separated by whitespace.
Returns
Return Value An HTMLCollection providing a live-updating list of every element which is a member of every class in names.
Usage Notes

As always, the returned collection is live, meaning that it always reflects the current state of the DOM tree rooted at the element on which the function was called. As new elements that match names are added to the subtree, they immediately appear in the collection. Similarly, if an existing element that doesn't match names has its set of classes adjusted so that it matches, it immediately appears in the collection.

The opposite is also true; as elements no longer match the set of names, they are immediately removed from the collection.

Note: In quirks mode, the class names are compared in a case-insensitive fashion. Otherwise, they're case sensitive.

To look for elements that include among their classes a single specified class, we just provide that class name when calling getElementsByClassName():

element.getElementsByClassName("test");

This example finds all elements that have a class of test, which are also a descendant of the element that has the id of main:

document.getElementById("main").getElementsByClassName("test");

To find elements whose class lists include both the red and test classes:

element.getElementsByClassName("red test");

Examining The Results

You can use either the item() method on the returned HTMLCollection or standard array syntax to examine individual elements in the collection. However, the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed.

const matches = element.getElementsByClassName("colorbox"); for (let i = 0; i < matches.length; i++) { matches[i].classList.remove("colorbox"); matches.item(i).classList.add("hueframe"); }

Instead, use another method, such as:

const matches = element.getElementsByClassName("colorbox"); while (matches.length > 0) { matches.item(0).classList.add("hueframe"); matches[0].classList.remove("colorbox"); }

This code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation). Another element (if any are left) will then become item(0).

Filtering The Results Using Array Methods

We can also use Array methods on any HTMLCollection by passing the HTMLCollection as the method's this value. Here we'll find all <div> elements that have a class of test:

const testElements = document.getElementsByClassName("test"); const testDivs = Array.prototype.filter.call( testElements, (testElement) => testElement.nodeName === "DIV" );


 

getElementsByTagName()

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name.

All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically. Therefore, there is no need to call Element.getElementsByTagName() with the same element and arguments repeatedly if the DOM changes in between calls.

When called on an HTML element in an HTML document, getElementsByTagName lower-cases the argument before searching for it. This is undesirable when trying to match camel-cased SVG elements (such as <linearGradient>) in an HTML document. Instead, use Element.getElementsByTagNameNS(), which preserves the capitalization of the tag name.

Element.getElementsByTagName is similar to Document.getElementsByTagName(), except that it only searches for elements that are descendants of the specified element.

getElementsByTagName(tagName)

Parameters
Parameter Description
tagName The qualified name to look for. The special string "*" represents all elements. For compatibility with XHTML, lower-case should be used.
Returns
Return Value A live HTMLCollection of elements with a matching tag name, in the order they appear. If no elements are found, the HTMLCollection is empty.

// CHECK THE STATUS OF EACH DATA CELL IN A TABLE const table = document.getElementById("forecast-table"); const cells = table.getElementsByTagName("td"); for (const cell of cells) { const status = cell.getAttribute("data-status"); if (status === "open") { // GRAB THE DATA } }


 

hasAttribute()

The Element.hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.

hasAttribute(name)

Parameters
Parameter Description
name is a string representing the name of the attribute.
Returns
Return Value A Boolean

const foo = document.getElementById("foo"); if (foo.hasAttribute("bar")) { // DO SOMETHING }

Element Attribute DOM Methods
Not namespace-aware
(Most commonly used methods)
setAttribute (DOM 1)
getAttribute (DOM 1)
hasAttribute (DOM 2)
removeAttribute (DOM 1)
Namespace-aware variants
(DOM Level 2)
setAttributeNS
getAttributeNS
hasAttributeNS
removeAttributeNS
DOM Level 1 methods for dealing with Attr nodes directly
(seldom used)
setAttributeNode
getAttributeNode
removeAttributeNode
DOM Level 2 namespace-aware methods for dealing with Attr nodes directly
(seldom used)
setAttributeNodeNS
getAttributeNodeNS

 

hasAttributes()

The hasAttributes() method of the Element interface returns a boolean value indicating whether the current element has any attributes or not.

hasAttributes()

Returns
Return Value A Boolean

let foo = document.getElementById("foo"); if (foo.hasAttributes()) { // DO SOMETHING WITH 'foo.attributes' }


 

insertAdjacentElement()

The insertAdjacentElement() method of the Element interface inserts a given element node at a given position relative to the element it is invoked upon.

insertAdjacentElement(position, element)

Parameters
Parameter Description
position A string representing the position relative to the targetElement; must match (case-insensitively) one of the following strings:
 
'beforebegin': Before the targetElement itself.
'afterbegin': Just inside the targetElement, before its first child.
'beforeend': Just inside the targetElement, after its last child.
'afterend': After the targetElement itself.
element The element to be inserted into the tree.
Returns
Return Value The element that was inserted, or null, if the insertion failed.
Exceptions
SyntaxError DOMException Thrown if the position specified is not a recognized value.
TypeError Thrown if the element specified is not a valid element.

<!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->

Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

beforeBtn.addEventListener("click", () => { const tempDiv = document.createElement("div"); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement("beforebegin", tempDiv); } setListener(tempDiv); }); afterBtn.addEventListener("click", () => { const tempDiv = document.createElement("div"); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement("afterend", tempDiv); } setListener(tempDiv); });

<!DOCTYPE html> <html lang="en"> <head> <title>insertAdjacentElement() demo</title> <style> div { width: 50px; height: 50px; margin: 3px; border: 3px solid black; display: inline-block; background-color: red; } </style> </head> <body> <p>Click colored box to select it, then use the first two buttons below to insert elements before and after your selection.</p> <section> <div></div><div></div><div></div><div></div> </section> <button class="before">Insert before</button> <button class="after">Insert after</button> <button class="reset">Reset demo</button> </body> </html>

const beforeBtn = document.querySelector('.before'); const afterBtn = document.querySelector('.after'); const resetBtn = document.querySelector('.reset'); const container = document.querySelector('section'); let activeElem; resetBtn.addEventListener('click', () => { while (container.firstChild) { container.removeChild(container.firstChild); } for (let i = 0; i <=3; i++) { let tempDiv = document.createElement('div'); container.appendChild(tempDiv); setListener(tempDiv); } }); beforeBtn.addEventListener('click', function() { let tempDiv = document.createElement('div'); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement('beforebegin',tempDiv); } setListener(tempDiv); }); afterBtn.addEventListener('click', function() { let tempDiv = document.createElement('div'); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement('afterend',tempDiv); } setListener(tempDiv); }); function setListener(elem) { elem.addEventListener('click', function() { const allElems = document.querySelectorAll('section div'); for (let i = 0; i < allElems.length; i++) { allElems[i].style.border = '3px solid black'; } elem.style.border = '3px solid aqua'; activeElem = elem; }) }; function randomColor() { function random() { const result = Math.floor(Math.random() * 255); return result; } return 'rgb(' + random() + ',' + random() + ',' + random() + ')'; } function init() { const initElems = document.querySelectorAll('section div'); for (let i = 0; i < initElems.length; i++) { setListener(initElems[i]); } }; init();


 

insertAdjacentHTML()

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.

insertAdjacentHTML(position, text)

Parameters
Parameter Description
position A string representing the position relative to the element. Must be one of the following strings:
 
"beforebegin"
Before the element. Only valid if the element is in the DOM tree and has a parent element.
 
"afterbegin"
Just inside the element, before its first child.
 
"beforeend"
Just inside the element, after its last child.
 
"afterend"
After the element. Only valid if the element is in the DOM tree and has a parent element.
text The string to be parsed as HTML or XML and inserted into the tree.
Returns
Return Value None (undefined).
Exceptions
NoModificationAllowedError DOMException Thrown if position is "beforebegin" or "afterend" and the element either does not have a parent or its parent is the Document object.
SyntaxError DOMException Thrown if position is not one of the four listed values.
Notes

The insertAdjacentHTML() method does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.

We can visualize the possible positions for the inserted content as follows:

<!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->

Security Considerations

When inserting HTML into a page by using insertAdjacentHTML(), be careful not to use user input that hasn't been escaped.

You should not use insertAdjacentHTML() when inserting plain text. Instead, use the Node.textContent property or the Element.insertAdjacentText() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.

<select id="position"> <option>beforebegin</option> <option>afterbegin</option> <option>beforeend</option> <option>afterend</option> </select> <button id="insert">Insert HTML</button> <button id="reset">Reset</button> <p> Some text, with a <code id="subject">code-formatted element</code> inside it. </p>

code { color: red; }

const insert = document.querySelector("#insert"); insert.addEventListener("click", () => { const subject = document.querySelector("#subject"); const positionSelect = document.querySelector("#position"); subject.insertAdjacentHTML( positionSelect.value, "<strong>inserted text</strong>" ); }); const reset = document.querySelector("#reset"); reset.addEventListener("click", () => { document.location.reload(); });


 

insertAdjacentText()

The insertAdjacentText() method of the Element interface, given a relative position and a string, inserts a new text node at the given position relative to the element it is called from.

insertAdjacentText(where, data)

Parameters
Parameter Description
where A string representing the position relative to the element the method is called from; must be one of the following strings:
 
'beforebegin': Before the element itself.
 
'afterbegin': Just inside the element, before its first child.
 
'beforeend': Just inside the element, after its last child.
 
'afterend': After the element itself.
data A string from which to create a new text node to insert at the given position where relative to the element the method is called from.
Returns
Return Value None (undefined).
Exceptions
SyntaxError DOMException Thrown if where is not a recognized value.

<!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->

Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

beforeBtn.addEventListener("click", () => { para.insertAdjacentText("afterbegin", textInput.value); }); afterBtn.addEventListener("click", () => { para.insertAdjacentText("beforeend", textInput.value); });


 

matches()

The matches() method of the Element interface tests whether the element would be selected by the specified CSS selector.

matches(selectors)

Parameters
Parameter Description
selectors A string containing valid CSS selectors to test the Element against.
Returns
Return Value true if the Element matches the selectors. Otherwise, false.
Exceptions
SyntaxError DOMException Thrown if selectors cannot be parsed as a CSS selector list.

<ul id="birds"> <li>Orange-winged parrot</li> <li class="endangered">Philippine eagle</li> <li>Great white pelican</li> </ul>

const birds = document.querySelectorAll("li"); for (const bird of birds) { if (bird.matches(".endangered")) { console.log(`The ${bird.textContent} is endangered!`); } }


 

prepend()

The Element.prepend() method inserts a set of Node objects or string objects before the first child of the Element. String objects are inserted as equivalent Text nodes.

prepend(param1) prepend(param1, param2) prepend(param1, param2, /* ... ,*/ paramN)

Parameters
Parameter Description
param1, ..., paramN A set of Node or string objects to insert.
Returns
Return Value None (undefined).
Exceptions
HierarchyRequestError DOMException Thrown when the node cannot be inserted at the specified point in the hierarchy.

let div = document.createElement("div"); let p = document.createElement("p"); let span = document.createElement("span"); div.append(p); div.prepend(span); console.log(div.childNodes); // NodeList [ <span>, <p> ]

let div = document.createElement("div"); div.append("Some text"); div.prepend("Headline: "); console.log(div.textContent); // "Headline: Some text"

let div = document.createElement("div"); let p = document.createElement("p"); div.prepend("Some text", p); console.log(div.childNodes); // NodeList [ #text "Some text", <p> ]

The prepend() method is not scoped into the with statement.

let div = document.createElement("div"); with (div) { prepend("foo"); } // ReferenceError: PREPEND IS NOT DEFINED


 

querySelector()

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.
If no matches are found, null is returned.

Note: The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes.

querySelector(selectors)

Parameters
Parameter Description
selectors A string containing one or more selectors to match. This string must be a valid CSS selector string; if it isn't, a SyntaxError exception is thrown.

Note: Characters that are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, be especially careful when writing string literals using these characters.

Returns
Return Value An Element object representing the first element in the document that matches the specified set of CSS selectors.
Null is returned if there are no matches.
 
If you need a list of all elements matching the specified selectors, you should use querySelectorAll() instead.
Exceptions
SyntaxError DOMException Thrown if the syntax of the specified selectors is invalid.
Usage Notes

If the specified selector matches an ID that is incorrectly used more than once in the document, the first element with that ID is returned.

CSS pseudo-elements will never return any elements, as specified in the Selectors API.

Escaping Special Characters

To match against an ID or selectors that do not follow standard CSS syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). As the backslash is also an escape character in JavaScript, if you are entering a literal string, you must escape it twice (once for the JavaScript string, and another time for querySelector()):

<div id="foo\bar"></div> <div id="foo:bar"></div>

console.log("#foo\bar"); // "#fooar" (\b is the backspace control character) document.querySelector("#foo\bar"); // Does not match anything console.log("#foo\\bar"); // "#foo\bar" console.log("#foo\\\\bar"); // "#foo\\bar" document.querySelector("#foo\\\\bar"); // Match the first div document.querySelector("#foo:bar"); // Does not match anything document.querySelector("#foo\\:bar"); // Match the second div

Examples

Finding The First Element Matching A Class

In this example, the first element in the document with the class "myclass" is returned:

const el = document.querySelector(".myclass");

Complex Selectors

Selectors can also be really powerful, as demonstrated in the following example. Here, the first <input> element with the name "login" (<input name="login"/>) located inside a <div> whose class is "user-panel main" (<div class="user-panel main">) in the document is returned:

const el = document.querySelector("div.user-panel.main input[name='login']");

Negation

As all CSS selector strings are valid, you can also negate selectors.
This will select an input with a parent div with the user-panel class but not the main class.

const el = document.querySelector( "div.user-panel:not(.main) input[name='login']" );


 

querySelectorAll()

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

querySelectorAll(selectors)

Parameters
Parameter Description
selectors A string containing one or more selectors to match against. This string must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. Multiple selectors may be specified by separating them using commas.

Note: Characters which are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, special care must be taken when writing string literals using these characters. See Escaping special characters for more information.

Returns
Return Value A non-live NodeList containing one Element object for each element that matches at least one of the specified selectors or an empty NodeList in case of no matches.

Note: If the specified selectors include a CSS pseudo-element, the returned list is always empty.

Exceptions
SyntaxError DOMException Thrown if the syntax of the specified selectors string is not valid.

Examples

Obtaining A List Of Matches

To obtain a NodeList of all of the <p> elements in the document:

const matches = document.querySelectorAll("p");

This example returns a list of all <div> elements within the document with a class of either note or alert:

const matches = document.querySelectorAll("div.note, div.alert");

Here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and which are located inside a container whose ID is test.

const container = document.querySelector("#test"); const matches = container.querySelectorAll("div.highlighted > p");

This example uses an attribute selector to return a list of the <iframe> elements in the document that contain an attribute named data-src:

const matches = document.querySelectorAll("iframe[data-src]");

Here, an attribute selector is used to return a list of the list items contained within a list whose ID is userlist which have a data-active attribute whose value is 1:

const container = document.querySelector("#userlist"); const matches = container.querySelectorAll("li[data-active='1']");

Accessing The Matches

Once the NodeList of matching elements is returned, you can examine it just like any array.
If the array is empty (that is, its length property is 0), then no matches were found.
Otherwise, you can use standard array notation to access the contents of the list. You can use any common looping statement, such as:

const highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach((userItem) => { deleteUser(userItem); });


 

remove()

The Element.remove() method removes the element from the DOM.

remove()

<div id="div-01">Here is div-01</div> <div id="div-02">Here is div-02</div> <div id="div-03">Here is div-03</div>

const element = document.getElementById("div-02"); element.remove(); // Removes the div with the 'div-02' id

Element.remove() Is Unscopable

The remove() method is not scoped into the with statement.

with (node) { remove(); } // ReferenceError: remove is not defined


 

removeAttribute()

The Element method removeAttribute() removes the attribute with the specified name from the element.

removeAttribute(attrName)

Parameters
Parameter Description
attrName A string specifying the name of the attribute to remove from the element. If the specified attribute does not exist, removeAttribute() returns without generating an error.
Returns
Return Value None (undefined).
Usage Notes

You should use removeAttribute() instead of setting the attribute value to null either directly or using setAttribute().
Many attributes will not behave as expected if you set them to null.

// Given: <div id="div1" align="left" width="200px"> document.getElementById("div1").removeAttribute("align"); // Now: <div id="div1" width="200px">


 

removeAttributeNode()

The removeAttributeNode() method of the Element interface removes the specified attribute from the element.

removeAttributeNode(attributeNode)

Parameters
Parameter Description
attributeNode The attribute node to remove from the element.
Returns
Return Value The attribute node that was removed.
Exceptions
NotFoundError DOMException Thrown when the element's attribute list does not contain the attribute node.

// Given: <div id="top" align="center" /> const d = document.getElementById("top"); const d_align = d.getAttributeNode("align"); d.removeAttributeNode(d_align); // align is now removed: <div id="top" />


 

scroll()

The scroll() method of the Element interface scrolls the element to a particular set of coordinates inside a given element.

scroll(x-coord, y-coord) scroll(options)

Parameters
Parameter Description
x-coord The pixel along the horizontal axis of the element that you want displayed in the upper left.
y-coord The pixel along the vertical axis of the element that you want displayed in the upper left.
OR
options A dictionary containing the following parameters:
 
  • top Specifies the number of pixels along the Y axis to scroll the window or element.
     
  • left Specifies the number of pixels along the X axis to scroll the window or element.
     
  • behavior Determines whether scrolling is instant or animates smoothly.
    This option is a string which must take one of the following values:
    • smooth: scrolling should animate smoothly
    • instant: scrolling should happen instantly in a single jump
    • auto: scroll behavior is determined by the computed value of scroll-behavior
Returns
Return Value None (undefined).

// Put the 1000th vertical pixel at the top of the element element.scroll(0, 1000);

Using options:

element.scroll({ top: 100, left: 100, behavior: "smooth", });


 

scrollBy()

The scrollBy() method of the Element interface scrolls an element by the given amount.

scrollBy(x-coord, y-coord) scrollBy(options)

Parameters
Parameter Description
x-coord The horizontal pixel value that you want to scroll by.
y-coord The vertical pixel value that you want to scroll by.
OR
options A dictionary containing the following parameters:
 
  • top Specifies the number of pixels along the Y axis to scroll the window or element.
     
  • left Specifies the number of pixels along the X axis to scroll the window or element.
     
  • behavior Determines whether scrolling is instant or animates smoothly.
    This option is a string which must take one of the following values:
    • smooth: scrolling should animate smoothly
    • instant: scrolling should happen instantly in a single jump
    • auto: scroll behavior is determined by the computed value of scroll-behavior
Returns
Return Value None (undefined).

// scroll an element element.scrollBy(300, 300);

Using options:

element.scrollBy({ top: 100, left: 100, behavior: "smooth", });


 

scrollIntoView()

The Element interface's scrollIntoView() method scrolls the element's ancestor containers such that the element on which scrollIntoView() is called is visible to the user.

scrollIntoView() scrollIntoView(alignToTop) scrollIntoView(scrollIntoViewOptions)

Parameters
Parameter Description
alignToTop Optional Boolean value:
  • If true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor.
    Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}.
    This is the default value.
  • If false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor.
    Corresponds to scrollIntoViewOptions: {block: "end", inline: "nearest"}.
scrollIntoViewOptions An Object with the following properties:
  • behavior (Optional)
    Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:
    • smooth: scrolling should animate smoothly
    • instant: scrolling should happen instantly in a single jump
    • auto: scroll behavior is determined by the computed value of scroll-behavior
  • block (Optional)
    Defines vertical alignment. One of start, center, end, or nearest. Defaults to start.
  • inline (Optional)
    Defines horizontal alignment. One of start, center, end, or nearest. Defaults to nearest.
Returns
Return Value None (undefined).

const element = document.getElementById("box"); element.scrollIntoView(); element.scrollIntoView(false); element.scrollIntoView({ block: "end" }); element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });

Notes

The element may not be scrolled completely to the top or bottom depending on the layout of other elements.


 

scrollTo()

The scrollTo() method of the Element interface scrolls to a particular set of coordinates inside a given element.

scrollTo(x-coord, y-coord) scrollTo(options)

Parameters
Parameter Description
x-coord is the pixel along the horizontal axis of the element that you want displayed in the upper left.
y-coord is the pixel along the vertical axis of the element that you want displayed in the upper left.
OR
options A dictionary containing the following parameters:
  • top Specifies the number of pixels along the Y axis to scroll the window or element.
  • left Specifies the number of pixels along the X axis to scroll the window or element.
  • behavior Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:
    • smooth: scrolling should animate smoothly
    • instant: scrolling should happen instantly in a single jump
    • auto: scroll behavior is determined by the computed value of scroll-behavior
Returns
Return Value None (undefined).

element.scrollTo(0, 1000);

Using options

element.scrollTo({ top: 100, left: 100, behavior: "smooth", });


 

setAttribute()

Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

To get the current value of an attribute, use getAttribute(); to remove an attribute, call removeAttribute().

setAttribute(name, value)

Parameters
Parameter Description
name A string specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document.
value A string containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string.

Boolean attributes are considered to be true if they're present on the element at all. You should set value to the empty string ("") or the attribute's name, with no leading or trailing whitespace. See the example below for a practical demonstration.

Since the specified value gets converted into a string, specifying null doesn't necessarily do what you expect. Instead of removing the attribute or setting its value to be null, it instead sets the attribute's value to the string "null". If you wish to remove an attribute, call removeAttribute().

Returns
Return Value None (undefined).
Exceptions
InvalidCharacterError DOMException The specified attribute name contains one or more characters which are not valid in attribute names.

In the following example, setAttribute() is used to set attributes on a <button>.

<button>Hello World</button>

const button = document.querySelector("button"); button.setAttribute("name", "helloButton"); button.setAttribute("disabled", "");

This Demonstrates Two Things:

 

setAttributeNode()

The setAttributeNode() method adds a new Attr node to the specified element.

setAttributeNode(attribute)

Parameters
Parameter Description
attribute Is the Attr node to set on the element.
Returns
Return Value The replaced attribute node, if any, returned by this function.

<div id="one" align="left">one</div> <div id="two">two</div>

let d1 = document.getElementById("one"); let d2 = document.getElementById("two"); let a = d1.getAttributeNode("align"); d2.setAttributeNode(a.cloneNode(true)); // Returns: 'left' alert(d2.attributes[1].value);

Notes

If the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned.

This method is seldom used, with Element.setAttribute() usually being used to change element's attributes.


 

toggleAttribute()

The toggleAttribute() method of the Element interface toggles a Boolean attribute (removing it if it is present and adding it if it is not present) on the given element.

toggleAttribute(name) toggleAttribute(name, force)

Parameters
Parameter Description
name A string specifying the name of the attribute to be toggled. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document.
force A boolean value which has the following effects:
  • if not specified at all, the toggleAttribute method "toggles" the attribute named name, removing it if it is present, or else adding it if it is not present
  • if true, the toggleAttribute method adds an attribute named name
  • if false, the toggleAttribute method removes the attribute named name
Returns
Return Value true if attribute name is eventually present, and false otherwise.
Exceptions
InvalidCharacterError DOMException The specified attribute name contains one or more characters which are not valid in attribute names.

In the following example, toggleAttribute() is used to toggle the disabled attribute of an <input>.

<input value="text" /> <button>toggleAttribute("disabled")</button>

const button = document.querySelector("button"); const input = document.querySelector("input"); button.addEventListener("click", () => { input.toggleAttribute("disabled"); });