Sabah Ali
Sabah Ali's Blog

Sabah Ali's Blog

JavaScript DOM Cheatsheet.

JavaScript DOM Cheatsheet.

Sabah Ali's photo
Sabah Ali
·May 11, 2021·

2 min read

What is the DOM in JavaScript?

Document Object Model (DOM), is an object-oriented representation of a web page, which can be modified with a scripting language such as JavaScript. The DOM is able to change the document style, content and structure.

DOM nodes

Copy of Untitled.png

To use the access the DOM we use the following syntax.

Get an element by id

var Hello = document.getElementById('#hello');

Get an element by class

var SomeClass = document.getElementByClass('.NameOfClass');

Get an element by tag name

var SomeTag = document.getElementByTagName('li');

A shorthand way of selecting classes and id's is by using the query selector function. querySelectorAll selects all classes and id with the same name


var SelectSomeClass= document.querySelectorAll('.SomeClass');
var SelectSomeID = document.querSelectorAll('#SomeID');

To select the first id or class in a HTML document querySelctor is used

var SelectID = document.querySelector('#SomeID');
var SelectClass = document.querySelector('.SomeClass');

Creating elements

To create a HTML element within JavaScript DOM the following syntax is used.

creating the ul

const UL = document.createElement('ul');

Adding a class or id to the ul


Create an li (child) to add to the ul (parent)

const Li = document.createElement('li');

Adding a class or id


Creating a text node

var TextNode = document.createTextNode('Adding text to the li, to be displayed in HTML')

Appending the textnode to the li

Li. appendChild(TextNode);

Appending the li to the ul as a child

document. querySelector('ul-SomeClassName').appendChild(li);

For more cheatsheets on JavaScript, check out my blog.

Share this