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 −
window.document.methodName();OR document.methodName();
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>document.addEventListener('mouseover',function(){ document.body.style.backgroundColor ='red';});</script></body></html></pre>
JavaScript document.write() Method
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.
<html><body><button onclick ="writeText()"> Add HTML</button><script>functionwriteText(){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. 36. getAttributeNode()It is used to get the attribute node object. 37. 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. 50. renameNode()It is used to rename the nodes. 51. open()This method opens a document for writing. 52. normalizeDocument()This method normalize an entire HTML document. 53. normalize()It removes empty text nodes, and joins adjacent text nodes from parent node. 54. adoptNode()This method adopts a node from another document into the current document. 55. addEventListener()It is used to set up a function that will be called whenever the specified event is delivered to the target. 56. execCommand()This method is used for executing a command specified on the editable section that is being selected by the user. 57. createTextNode()It is used to create a text node with the specified text. 58. createEvent()It is used for creating an event object whose event type is specified in the parameter. 59. createDocumentFragment()It creates a new empty document fragment which resides in memory. 60. createComment()This method is used for creating a comment node with the given text. 61. createAttribute()It is used to create an attribute with a specific name using JavaScript for an HTML element and return the Attr object. 62. close()It closes the output stream. 63. 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. 66. getElementById()It returns the element of the given ID. 67. 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.
Leave a Reply