DOM: Basic DOM Methods

By Xah Lee. Date: . Last updated: .

Here are the essential Document Object Model methods. Learn to use these and you will know 99% of practical DOM use.

Get Elements

document. currentScript
return the current script element.
document. getElementById(id)
Return a non-live element object or null.
document. getElementsByTagName(tag_name)
Return a live HTMLCollection.
document. getElementsByClassName(class_value)
Return a live HTMLCollection.
document. querySelector(css_selector)
Return a non-live HTMLCollection of the first element that matches.
document. querySelectorAll(css_selector)
Return a non-live HTMLCollection.

Examples:

DOM: Get Elements by ID, Tag, Name, Class, CSS Selector

Element Attribute

node.hasAttribute(attr)
Return true or false. This is especially useful for “boolean attributes” that doesn't have value, such as the attribute checked of input tag for checkboxes.
node.getAttribute(attr)
Return the value of element's attribute attr. If doesn't exist, returns null. The attr is any of {"id", "href", …}. [see DOM: Get Node Attribute Value]
node.setAttribute(attr, val)
Set the value of the attribute named attr to value val. If the attribute does not exist, it will be created. Return undefined. [see DOM: Set Node Attribute Value]
node.removeAttribute(attr)
Remove the attribute. No error if attribute doesn't exist. Return undefined. [see DOM: Remove Element's Attribute Value]
node.attributes
Get all attributes. Return a live Array-Like Object.

For HTML element's standard attributes, you can use a property directly.

html_element.attribute_name
Return element's attribute's value, or undefined if it doesn't exist.
html_element.attribute_name = value
Set a element's attribute. Return value. If attribute_name is not a standard html attribute, it's not added.
const x = document .getElementsByTagName("a")[0];

x.getAttribute("href");
// is equivalent to
x.href

Using property does not work with XML such as stroke="…" from SVG, or non-standard attributes such as data-xyz="…" from HTML5 Custom Data Attribute.

“class” Attribute

For the class attribute, there's more useful methods.

see DOM: List/Add/Remove Class Attribute

“style” Attribute

For the style attribute, you can use HTML Element properties.

Note, HTML Element properties may not work with XML, example: SVG's stroke. [see SVG: Specifying Styles]

node.style.css_attribute
Return the attribute value, or undefined if it doesn't exist.
node.style.css_attribute=value
Set css attribute. Return value. If attribute is not a standard css attribute, it's not added.

Example: DOM: Change CSS

Get Node {Type, Name, Value}

HTML element is a node. But node also includes white spaces between elements, comments, doctype, and arbitrary XML tags.

node.nodeType
A integer representing the type of the node node (1 means HTML element, 3 means text node).
node.nodeName
The name of the node node (either the name of tag (for example, P, DIV, SPAN, etc) or "#text")
node.nodeValue
The text value of text node or attribute node. Else, null.

[see DOM: Node Type, Node Name, Node Value]

Navigate Nodes

The following ignore whitespace nodes.

[see DOM: Whitespace Nodes]

node.previousElementSibling
Return null if none.
node.nextElementSibling
Return null if none.
node.firstElementChild
Return null if none.
node.lastElementChild
Return null if none.
node.hasChildNodes()
Return true or false.
node.children
Return read-only live object HTMLCollection. Value is all non-whitespace children of node. [see DOM: What Does Live Object Mean?]
node.parentElement
Return null if none.

[see DOM: Navigate DOM Tree]

The following do not ignore whitespace nodes.

Create New Nodes

document. createElement(tag_name)
Create a new tag_name element node. Return it.
document. createTextNode(str)
Create a new text node with the node value of string str.
node.cloneNode(true)
Return a copy of node, including all child nodes if argument is true.
node.innerHTML
The content of node as string. You can read or set this value. [see DOM: Difference Between textContent, innerHTML, innerText, nodeValue]

[see DOM: Create/Insert HTML Element]

{Insert, Remove, Replace} Nodes

node.insertAdjacentElement(position, new_node)
[see DOM: insertAdjacentElement]
p_node.appendChild(new_node)
Returns the argument new_node. [see DOM: .appendChild]
p_node.insertBefore(new_node, node_x)
Inserts new_node as a new child of p_node before node_x.
p_node.removeChild(old_node)
Removes the child old_node from p_node.
p_node.replaceChild(new_node, old_node)
Replaces the child node old_node of p_node with new_node. If new_node is in the same doc, it'll also be removed.

Examples:

Change Element's Text Content

There are 3 ways to change a element's content.

  1. Treat it as a innerHTML, and use property innerHTML . This is for HTML (not XML), works in all browsers.
  2. Treat it as a text content, and use property textContent . This works well if the content is text and contains no HTML. (if you set value to "<b>bold text</b>", the text won't be bold.)
  3. Treat it as a DOM tree node, and use property nodeValue. This is the most general, and works with XML too.

Example: DOM: Change Element's Content

Detail: DOM: Difference Between textContent, innerHTML, innerText, nodeValue

{Add, Remove} Event Handler

node.addEventListener(event, f, false)
Add the function f to the event event
node.removeEventListener(event, f )
Remove the function f that was attached to the event event

[see DOM: Add/Remove Event Handler]

Web Scripting Overview

  1. Browser Window Object, DOM
  2. Intro to Event-Based Programing
  3. JavaScript Load Order

DOM How-To

  1. Basic DOM Methods
  2. Get Element by ID, Tag, Name, Class, CSS
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Attribute Value
  8. Set Attribute Value
  9. Remove Attribute
  10. List/Add/Remove Class Attribute
  11. Add/Remove Event Handler
  12. Navigate DOM Tree
  13. Node Type, Name, Value

DOM HTML GUI

  1. Button
  2. Input Text Field
  3. Password Text Field
  4. Textarea
  5. Radio Button
  6. Checkbox
  7. Selection, Popup Menu
  8. Input Range Slider
  9. Color Picker

Web Scripting Examples

  1. Disable Right Click
  2. document.write
  3. Image Rollover
  4. Pop-up New Window
  5. Digital Clock
  6. Stopwatch
  7. Fade a Element
  8. How to Create Tooltip
  9. Falling Snow Effect
  10. Box Following Scroll

Web Scripting Misc

  1. Web Cookies
  2. Web Storage
  3. DOM: Open URL window.open
  4. Encode URL, Escape String
  5. Browser Info, Navigator Object
  6. Get URL (window.location)
  7. Find Window Width
  8. Find Element Width
  9. WebSocket
  10. Value of “this” in Event Handler
  11. Event Delegation
  12. Get Current Script Tag
  13. insertAfter Element
  14. Randomize List
  15. create Document Fragment
  16. innerHTML, nodeValue, textContent, innerText?
  17. What is Live Object
  18. NodeList vs HTMLCollection
  19. Whitespace Nodes

jQuery

  1. jQuery Basics
  2. jQuery() vs querySelectorAll()
  3. Write JQuery Plugin

node.js

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog