JavaScript HTML DOM Document Object

Document Object Properties

Complete DOM Document Methods

Finding HTML Elements

document.getElementById(id)

Finds an element by element id

Element with ID: find-by-id

document.getElementsByTagName(name)

Finds elements by tag name

Paragraph 1

Paragraph 2

document.getElementsByClassName(name)

Finds elements by class name

Element with class: test-class
Another element with class: test-class

document.querySelector(css selector)

Finds the first element that matches CSS selector

First .query-demo element
Second .query-demo element

document.querySelectorAll(css selector)

Finds all elements that match CSS selector

Changing HTML Elements

element.innerHTML

Changes the inner HTML of an element

Original content

element.attribute

Changes the attribute value of an HTML element

Demo image

element.style.property

Changes the style of an HTML element

Style me!

element.setAttribute(attribute, value)

Sets or changes the specified attribute

Check my attributes

element.textContent

Changes the textual content of an element

Original text

Adding and Deleting Elements

document.createElement(element)

Creates an HTML element

document.removeChild(element)

Removes an HTML element

Element 1 (click to remove)
Element 2 (click to remove)
Element 3 (click to remove)

document.appendChild(element)

Adds an HTML element

Existing content

document.replaceChild(new, old)

Replaces an HTML element

Old element (will be replaced)

element.remove()

Removes the element from DOM

Click to remove this element
Click to remove this element

Adding Events Handlers

element.addEventListener(event, function)

Attaches an event handler to an element

element.onclick = function

Assigns a click event handler

element.onmouseover / element.onmouseout

Mouse hover events

Hover over me!

element.onkeypress / element.onkeyup

Keyboard events

Finding HTML Objects

document.anchors

Returns all elements that have a name attribute

Section 1
Section 2

document.forms

Returns all

elements

document.images

Returns all elements

Image 1 Image 2

document.links

Returns all elements that have a href attribute

Link 1
Link 2

document.scripts

Returns all elements