The JavaScript DOM document object owns all objects in the webpage. It represents the webpage. When the webpage is loaded in the web browser, it creates an HTML DOM ‘document’ object. It is the root of the HTML document.
The DOM document object contains the various properties and methods you can use to get details about HTML elements and customize them. With document objects, JavaScript can access, and change document’s structure, content or style.
To access any HTML element, you should always start accessing with the DOM document object.
Accessing DOM Document Object
The webpage is represented as the DOM document object. If we want to access any element in the webpage, we need to first start accessing the document object. In JavaScript, the document object is a property of the window object. So we can access the document object as a property of window object using window.document syntax. We can also access it without writing window.
window.document
or simply
document
This interactive example will help you understand the working of document.getElementById() method.
Window Document Object
The URL Property
Extract URL
JavaScript DOM Document Methods
List of JavaScript DOM document methods are −
Sr.No
Method & Description
1.
writeln()This method provides the functionality to write HTML or JavaScript expressions directly to a document. It adds a newline character after each statement.
2.
write()This method provides the functionality to write HTML or JavaScript expressions directly to a document.
3.
hasFocus()It is used for determining if the document or any element inside the document has focus or not.
4.
renameNode()It is used to rename the nodes.
5.
open()This method opens a document for writing.
6.
normalizeDocument()This method normalize an entire HTML document.
7.
normalize()It removes empty text nodes, and joins adjacent text nodes from parent node.
8.
adoptNode()This method adopts a node from another document into the current document.
9.
addEventListener()It is used to set up a function that will be called whenever the specified event is delivered to the target.
10.
execCommand()This method is used for executing a command specified on the editable section that is being selected by the user.
11.
createTextNode()It is used to create a text node with the specified text.
12.
createEvent()It is used for creating an event object whose event type is specified in the parameter.
13.
createDocumentFragment()It creates a new empty document fragment which resides in memory.
14.
createComment()This method is used for creating a comment node with the given text.
15.
createAttribute()It is used to create an attribute with a specific name using JavaScript for an HTML element and return the Attr object.
16.
close()It closes the output stream.
20.
getElementsByTagName()It is a read-only method which is used to get the collection of all the elements in the document having the specified tag name in parameter.
21.
getElementsByName()This method is used to return collection of elements with the name attribute specified in the parameter.
22.
getElementsByClassName()This method is used for getting the collection of all the elements in the document with specified class name.
23.
getElementById()It returns the element of the given ID.
24.
createElement()This method creates an HTML element specified by tag name or element name.
JavaScript DOM Document Properties
In the following table, we have listed JavaScript DOM document properties −
Sr.No
Properties & Description
1.
URLIt is a read-only property which returns the complete URL of the document including the protocol.
2.
titleThis property is used to set or get the title of the document.
3.
strictErrorCheckingIt is used to determine whether document enforce strict error checking or not.
4.
scriptsIt is a read-only property used for returning all the script elements present within HTML document as a collection.
5.
linksThe links is a read-only property which returns a collection of all the links corresponding to a and area elements with href attribute.
6.
lastModifiedThis property returns the date and time of the current document when it was last modified.
7.
inputEncodingThe inputEncoding property returns a String which represents the documents character encoding.
8.
implementationThis returns a DOMImplementation object which is associated with the current document.
9.
imagesIt is a read-only property used for returning all the img elements present within HTML document as a collection.
10.
headThe head property returns the HTML head element.
11.
formsThe forms is a read-only property used for returning all the form elements present within HTML document as a collection.
12.
embedsIt is a read-only property which returns all the embed elements present within HTML document as a collection.
13.
domConfigThis property is deprecated due to which will return undefined in all new browsers.
14.
domainIt is used for getting the domain name of the server on which the document is currently being executed.
15.
documentURIThis property is used to set or return the document’s location.
16.
documentModeThe documentMode property is an IE8 property which determines the rendering mode used by browser.
17.
documentElementIt returns the documentElement as an Element Object.
18.
doctypeThis property returns the DTD (Document Type Declaration) that are associated with the current HTML document.
19.
designModeIt helps us to determine if the entire document is editable or not.
20.
defaultViewIt is used for returning document’s window object.
21.
cookieThe HTML DOM document cookie property is used for creating, reading and deleting cookies.
22.
charsetIt returns the character encoding of the HTML document.
23.
appletsIt is used to return a list of all the applets elements within a document but this property is now deprecated.
24.
characterSetThis property is used to get character encoding of the document.
25.
anchorsThe anchors property is a read only property which lists all the “a” tag with name attribute in the document.
26.
baseURIIt is used to return the base Uniform Resource Identifier (URI) of the document.
Here, we have explained some properties of the HTML DOM ‘document’ object with examples in JavaScript.
Document childElementCount Property
In JavaScript, the childElementCount property of the document object returns the count of the child elements of the document.
Syntax
Follow the syntax below to use the childElementCount property of document object in JavaScript.
document.childElementCount;
Example
In the below code, the childElementCount property returns 1, as the document contains only 1 child element,. Other HTML elements are the child of the body.
<html><body><div>First Element</div><div>Second Element</div><div>Third Element</div><div id ="output"></div><script>
document.getElementById('output').innerHTML ="Total number of child elements in the document is: "+ document.childElementCount;</script></body></html></pre>
Output
First Element
Second Element
Third Element
Total number of child elements in the document is: 1
Document Links Property
The Document Links property returns the collection of all links of the document. After that, you can use the for...of loop to traverse the collection of links.
Syntax
Follow the syntax below to use the document 'links' property in JavaScript.
document.links;
Example
In the below code, the web page contains the two <a> elements. We access their href attribute's value using the links property.
After that, we used the for...of loop to traverse the collection of links and print them on the web page.
<html><body><div><a href ="https://tutorialspoint.com/"> Home </a></div><div><a href ="https://www.tutorialspoint.com/articles/category/javascript"> JavaScript </a></div><div id ="output"></div><script>const allLinks = document.links;
document.getElementById("output").innerHTML +="The webpage contains the below links. <br>";for(let link of allLinks){
output.innerHTML += link +"<br>";}</script></body></html></pre>
Output
Home
JavaScript
The webpage contains the below links.
https://tutorialspoint.com/
https://www.tutorialspoint.com/articles/category/javascript
Document Title Property
In JavaScript, the DOM document title property returns the title of the web page.
Syntax
Follow the syntax below to access the DOM document title of the web page.
document.title;
Example
In the below code, we have added the <title> tag in the <head> tag.
After that, we used the 'title' property of the document to access the web page's title.
<html><head><title> JavaScript -HTMLDOM Document </title></head><body><div id ="output">The title of the document is:</div><script>
In JavaScript, DOM methods are used to perform a particular action on HTML elements. The DOM represents a HTML document or web page with a logical tree. In the tree, each branch ends in a node, and each node contains objects. DOM methods allow us programmatic access to the tree. Using the DOM methods, you can change the document’s structure, style, or content.
For example, you can use DOM methods to access HTML elements using id, attribute, tag name, class name, etc., add events to the document or HTML elements, add new HTML elements to the DOM, etc.
Syntax
Following is the syntax to access and execute the DOM method in JavaScript −
You may or may not use the ‘window’ object to access the document object’s method.
Here, we have explained some HTML DOM methods with examples and covered other methods in the reference.
JavaScript document.getElementById() Method
The JavaScript getElementById() method of the document object is the most popular method to access the HTML elements using the id.
Syntax
Follow the syntax below to use the document.getElementById() method.
const ele = document.getElementById("id");
The getElementById() method takes an id of the HTML element as a parameter.
Example
In the below code, the id of the ‘div’ element is ‘output’.
In JavaScript, we use the document.getElementById() method to access the div element using its id.
Also, we use the ‘innerHTML’ property of the element to add extra HTML to the ‘div’ element.
<html><body><button onclick ="accessEle()"> Access output and write </button><p id ="output"></p><script>functionaccessEle(){
document.getElementById("output").innerHTML ="Hello User! You have just clicked the button!";}</script></body></html></pre>
JavaScript document.addEventListener() Method
The addEventListener() method is used to add the event to the document.
Syntax
Follow the syntax below to use the addEventListener() method with a document.
document.addEventListener('mouseover',function(){// Perform action on the document.});
The addEventListener() method takes the event name as the first parameter and the callback function as a second parameter.
Example
In the below code, we added the 'mouseover' event to the document. Whenever you hover over the document, it will change the background color of the document body to red.
<html><body><h3>JavaScript document.addEventListener() Method </h3><p> Hover over here to change background color </p><script>
The document.write() method adds the text or HTML to the document. It replaces the content of the document with the HTML passed as an argument of the method.
Syntax
Follow the syntax below to use the document.write() method.
document.write(HTML)
You can replace the 'HTML' argument with the text or HTML.
Example
In the below code, we execute the writeText() function when you click the button.
In the function, we use the document.write() method to add HTML to the web page. It replaces the HTML of the whole web page.
document.write("<p>Hello Users, Text is written using the document.write() method. </p>");}</script></body></html></pre>
List of DOM Methods
In the below table, we have listed all methods related to the HTML DOM −
Sr.No
Method & Description
1.
toString()It is used to convert an HTML element into a string format.
2.
setAttribute()This method allows you to define attributes for a particular element.
3.
setAttributeNode()This method allows you to define a particular attribute node on a particular element.
4.
scrollIntoView()It ensures that a particular element on a web page of scrollable container becomes visible by adjusting the scroll position.
5.
querySelector()It is used to select and access the first HTML element that matches a given CSS selector(s) within the document.
6.
querySelectorAll()This method allows you to select and access all HTML element that matches a given CSS selector(s) within the document.
7.
remove()This method can delete an element completely from the web page.
8.
removeAttribute()This method is used to delete any attribute that has been set on an HTML element within the DOM structure.
9.
removeAttributeNode()It allows you to delete a specific attribute node from an element.
10.
removeChild()It is used to delete the selected child element from its parent element.
11.
removeEventListener()This method allows you to delete an event listener that was previously assigned to an element.
12.
replaceChild()This method enable us to replace one child element with another in a parent element.
13.
hasAttribute()It is used to check whether an attribute exists within an HTML element.
14.
hasAttributes()This method checks whether an element in HTML DOM has attributes.
15.
hasChildNodes()It is used to check if an HTML element has any child element inside it.
16.
getAttribute()It returns the value of a specified attribute that belongs to an HTML element.
17.
getBoundingClientRect()This method is used to get the size of an element and its position relative to the viewport.
18.
closest()This method returns the closest ancestor of the current element (or the current element itself) that matches a given CSS selector. If no such ancestor exists, it returns null.
19.
contains()You can check if a DOM Element contains another element within its subtree using this method.
20.
click()The click() method activates a mouse click on an element.
21.
normalize()It is used to combine adjacent text nodes within an HTML element by removing any empty text nodes.
22.
isDefaultNamespace()It is used to check if a specific namespace URI is the default namespace for elements within a document or element.
23.
isEqualNode()This method checks if two nodes are equal by comparing their attributes, types, and child nodes.
24.
isSameNode()It checks whether two node references point to the same node object within an HTML document.
25.
isSupported()This method is used to check if a web browser can supports or handle a particular feature or functionality on a web page.
26.
insertAdjacentElement()This method allows you to insert a new HTML element exactly where you need it relative to another element on a webpage.
27.
insertBefore()This method allows you to add a new child element inside a parent element, specifying its position relative to another child element.
28.
blur()This method allows you to dynamically remove focus from an element in the HTML DOM.
29.
matches()This method checks if an element matches a given CSS selectors.
30.
insertAdjacentHTML()It helps you to insert a specified HTML code at a specific position relative to the element that calls this method.
31.
addEventListener()It is used to register event handlers to elements.
32.
cloneNode()It duplicates a node, including it's attributes and child nodes.
33.
appendChild()This method is used to add a new child node(element) as the last child node of the specified parent node.
34.
compareDocumentPosition()It enables understanding of document structure by comparing the positions of two DOM elements(nodes) and returns a bitmask(numeric value).
35.
focus()This method sets focus to specific webpage elements.
getBoundingClientRect()This method is used to get the size of an element and its position relative to the viewport.
38.
getElementsByClassName()This method retrieves a live HTMLCollection of elements that match a specified class name within a document or a specific element.
39.
getElementsByTagName()It retrieves a live HTMLCollection of elements that match a specified tag name.
40.
insertAdjacentText()It allows you to insert a text content at a specific position relative to the element that calls this method.
41.
namedItem()It is used to get the first element of collection whose id or name matches with the name mentioned in parameter.
42.
item()It returns the element from the HTMLCollection located at specified index in parameter.
43.
entries()This method retrieves an iterator, that allows us to iterate through all the key/value pairs in the object.
44.
forEach()This method calls the callback function mentioned in the parameter once for each value pair in the list in the order of their insertion.
45.
item()This method retrieves a node from the NodeList specified by the index in the parameter.
46.
keys()This method retrieves an iterator that allows us to go through all the keys contained in the NodeList.
47.
writeln()This method provides the functionality to write HTML or JavaScript expressions directly to a document. It adds a newline character after each statement.
48.
write()This method provides the functionality to write HTML or JavaScript expressions directly to a document.
49.
hasFocus()It is used for determining if the document or any element inside the document has focus or not.
getElementsByTagName()It is a read-only method which is used to get the collection of all the elements in the document having the specified tag name in parameter.
64.
getElementsByName()This method is used to return collection of elements with the name attribute specified in the parameter.
65.
getElementsByClassName()This method is used for getting the collection of all the elements in the document with specified class name.
createElement()This method creates an HTML element specified by tag name or element name.
68.
add()This method adds one or more tokens specified in the parameter to the DOMTokenList.
69.
contains()This method checks whether the list contains the specified token, and returns a boolean value accordingly.
70.
entries()This method returns an iterator that is allowing to go through all the key/value pairs.
71.
forEach()This method calls the callback function mentioned in the parameter once for each value pair in the list in the order of their insertion.
72.
item()This method returns a token from the DOMTokenList specified by the index in the parameter.
73.
keys()This method returns an iterator which allows you to go through all the keys contained in the token list.
74.
remove()This method removes one or more tokens specified in the parameter to the DOMTokenList.
75.
replace()This method replaces the existing token in DomTokenList with a new token specified in the parameter.
76.
supports()This method checks whether the token specified in the parameter is supported in DOMTokenList.
77.
toggle()This method dynamically adds or removes a token or class from an element class attribute.
78.
values()This method returns an iterator allowing us to go through all values contained in the token list.
List of DOM Properties
The below table shows all properties related to the HTML DOM −
Sr.No
Method & Description
1.
titleIt helps us to access and update the value stored in an element's title attribute.
2.
textContentThis property is used to access and update the text content of an HTML element and all its child elements as a single string.
3.
tagNameIt gives you the name of the HTML tag in uppercase that defines an element on a webpage.
4.
styleUsing this property, you can get the CSS styles that are directly set for a particular element.
5.
tabIndexIt is used to access and update the value of the tabIndex attribute for an element.
6.
scrollLeftThis property is used to access and update how far an element's content is scrolled horizontally.
7.
scrollTopIt is used to access and update how far an element's content is scrolled vertically.
8.
scrollWidthThis property gives you the total horizontal width of an element's content in pixels.
9.
scrollHeightYou can get the total vertical height of an element's content in pixels using this property.
10.
idThe id property is used for setting and retrieving the value of the element's id attribute.
11.
innerTextIt allows us to retrieve or change the visible text content directly within an HTML element on a web page.
12.
isContentEditableIt is used to check if a webpage element can be edited by users directly.
13.
langThe lang property is an attribute of an HTML element that specifies the language code.
14.
lastChildThe lastChild property returns a node that points to the last child node of a specific parent element.
15.
lastElementChildIt returns a node that holds the last child element of a parent element.
16.
namespaceURIThe namespaceURI property of an element provides the namespace URI assigned to the element.
17.
nextElementSiblingUsing this property, you can get the immediate next node in the sequence of a particular element.
18.
nextSiblingIt is used to access the immediate next node in sequence from the current node within the DOM tree.
19.
nodeNameThis property is used to identify a node's type and name based on its content.
20.
nodeTypeThe nodeType Property returns an integer value representing the type of a node.
21.
nodeValueIt is used for accessing and updating the value of a node.
22.
offsetHeightThis property is used to get the complete visible height of that element on the webpage, including both its vertical padding and borders, measured in pixels.
23.
offsetLeftIt returns the pixel based measurement of the distance from the element's left boundary to its nearest positioned parent's left boundary.
24.
offsetParentIt is used to find the closest ancestor element that affects the positioning of another element.
25.
offsetWidthThe offsetWidth property of an element gives you the total visible width of that element on the webpage.
26.
outerHTMLThe outerHTML property fetches the entire HTML code of an element.
27.
outerTextThis property can access or update the text content of an HTML element, including all its nested text and elements.
28.
ownerDocumentIt gives you the object for the document node that contains a specific element.
29.
parentElementIt allows you to access the immediate parent element of a particular element within the HTML element.
30.
parentNodeThis property is used to access the immediate parent node of a particular node within the HTML element.
31.
classListIt acts as an active container that holds a collection of CSS classes assigned to an element's class attribute.
32.
childNodesIt is used to retrieve all child nodes of an element, including elements, text nodes, and comments.
33.
classNameYou can access or modify the value of the class attribute of an element using this property.
34.
clientTopIt is used to get the accurate element positioning and size calculation in webpage layouts.
35.
firstElementChildIt provides the first child element within a given parent element.
36.
offsetTopUsing this property, you can get the pixel-based vertical distance from the element's top edge of its nearest positioned ancestor's top edge.
37.
attributesIt returns 'NameNodeMap' containing the collection of attributes of an HTML element
38.
accesskeyThis property allows you to assign a keyboard shortcut to an element on a webpage.
39.
firstChildIt helps you to access the very first child node of a given parent element in the HTML DOM.
40.
innerHTMLThis property allows us to read the existing HTML content of an element and update it with new HTML content.
41.
dirIt provides access for setting and retrieving the value of dir attributes of any element in HTML.
42.
contentEditableYou can make text content inside the HTML elements editable using this property.
43.
clientWidthIt returns the width of an element, including padding but excluding margin, border, or scrollbar width.
44.
clientLeftThis property is used to get the width of an element's left border, excluding left padding or margin.
45.
clientHeightIt is used to get the inner height of an element, including padding but not margin, border, or scrollbar width.
46.
childrenThis property returns a collection of child elements.
47.
childElementCountIt returns the count of direct child elements of a specified element.
48.
srcThis property used for elements like <img>, <script>, or <iframe> to get or set the source URL.
49.
hrefThis property is used for anchor <a> elements to get or set the hyperlink reference.
50.
checkedThis property is used to get or set the checked state of a checkbox or radio button.
51.
disabledThis property is used to get or set the disabled state of an input element.
52.
lengthIt returns the number of elements in an HTMLCollection.
53.
lengthThis method returns the number of items in the NodeList.
54.
valueThis property is used to set or get the value of an attribute.
55.
specifiedIt checks whether the mentioned attribute is specified or not.
56.
nameIt is used get the name of the used attribute on an element.
57.
isIdThis property determines whether a HTML attribute is an 'id' attribute or not.
58.
URLIt is a read-only property which returns the complete URL of the document including the protocol.
59.
titleThis property is used to set or get the title of the document.
60.
strictErrorCheckingIt is used to determine whether document enforce strict error checking or not.
61.
scriptsIt is a read-only property used for returning all the script elements present within HTML document as a collection.
62.
linksThe links is a read-only property which returns a collection of all the links corresponding to a and area elements with href attribute.
63.
lastModifiedThis property returns the date and time of the current document when it was last modified.
64.
inputEncodingThe inputEncoding property returns a String which represents the documents character encoding.
65.
implementationThis returns a DOMImplementation object which is associated with the current document.
66.
imagesIt is a read-only property used for returning all the img elements present within HTML document as a collection.
67.
headThe head property returns the HTML head element.
68.
formsThe forms is a read-only property used for returning all the form elements present within HTML document as a collection.
69.
embedsIt is a read-only property which returns all the embed elements present within HTML document as a collection.
70.
domConfigThis property is deprecated due to which will return undefined in all new browsers.
71.
documentURIThis property is used to set or return the document's location.
72.
documentModeThe documentMode property is an IE8 property which determines the rendering mode used by browser.
73.
documentElementIt returns the documentElement as an Element Object.
74.
doctypeThis property returns the DTD (Document Type Declaration) that are associated with the current HTML document.
75.
designModeIt helps us to determine if the entire document is editable or not.
76.
defaultViewIt is used for returning document's window object.
77.
cookieThe HTML DOM document cookie property is used for creating, reading and deleting cookies.
78.
charsetIt returns the character encoding of the HTML document.
79.
appletsIt is used to return a list of all the applets elements within a document but this property is now deprecated.
80.
characterSetThis property is used to get character encoding of the document.
81.
anchorsThe anchors property is a read only property which lists all the "a" tag with name attribute in the document.
82.
baseURIIt is used to return the base Uniform Resource Identifier (URI) of the document.
83.
lengthThis method returns the number of tokens in a token list.
84.
valueThis method returns the DOMTokenList serialized as a string.
85.
domainIt is used for getting the domain name of the server on which the document is currently being executed.
The HTML DOM allows JavaScript to access and modify the content of HTML elements. JavaScript can change all HTML elements, attributes, CSS styles in the page. JavaScript can also add, remove the HTML elements and attributes. Using JavaScript, we can even create new events in the page.
Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
What is DOM?
The DOM is an acronym for the Document Object Model. It is a programming interface for Core, XML, and HTML DOM.
It is a W3C (World Wide Web Consortium) standard.
The DOM defines the logical or tree-like structure of the web page or document. In the tree, each branch ends in a node, and each node contains objects. DOM methods allow us programmatic access to the tree. Using the DOM methods, you can change the document’s structure, content or style.
What is HTML DOM?
HTML creates the web page’s structure, and JavaScript adds interaction to the web page by manipulating the HTML elements.
JavaScript cant interact directly with HTML elements. So, whenever a web page loads in the browser, it creates a DOM.
So, the document object represents the HTML document displayed in that window. Furthermore, each iframe in the webpage creates a new DOM. The Document object has various properties that refer to other objects that allow access to and modify document content.
The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
Window object − It represents the current window of the browser. It also works as a global object for the browser window. It is at the top of the hierarchy. It is the outmost element of the object hierarchy.
Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page. It is used to access and modify the elements of the web page.
Form object − Everything enclosed in the <form>…</form> tags sets the form object.
Form control elements − The form object contains all the elements defined for that object, such as text fields, buttons, radio buttons, and checkboxes.
Here is a simple hierarchy of a few important objects −
There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content.
The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.
There are three different types of the DOM according to the W3C.
Core DOM − It is a standard model for all document types.
HTML DOM − It is a standard model for HTML documents.
XML DOM − It is a standard model for XML documents.
Why is DOM required?
As discussed above, when a web page is loaded into the browser window, it becomes a document object.
After that, JavaScript can access the HTML elements and perform the other operations on them. It means JavaScript can interact with the web page using the HTML DOM.
For example, JavaScript can perform the below operations on HTML elements using the document object.
Access HTML elements
Replace HTML elements
Add New HTML elements
Delete HTML elements
Change CSS of HTML elements
Change attributes of HTML elements
Add animation to HTML elements
Add events to HTML elements
However, there are other uses of the document object, which we will cover in upcoming chapters.
DOM Interfaces
The DOM interfaces are the actual components of the DOM that work with JavaScript or any other programming language to manipulate the web page. They provide various methods and properties to interact with and manipulate web pages.