CSE 154: Web Programming
Lecture 8 JS “Cheat Sheet”
This reference summarizes the most useful methods/properties used so far CSE 154. It is not an exhaustive
reference for everything in JavaScript (for example, there exist many more w indowmethods/properties than are
shown below), but provide most functions/properties we have seen so far.
The Module Pattern
Whenever writing JavaScript, you should use the module pattern, wrapping the content of the code (window
load e
vent handler and other functions) in an anonymous function. Below is a template for reference:
“use strict”;
(function() {
// any module-globals (limit the use of these when possible)
window.addEventListener(“load”, init);
function init() {
...
}
// other functions
})();
Handy Alias Functions
The following four shorthand functions will be used frequently in the class (to use, make sure they are defined in
the module pattern of your JS program).
function id(idName) {
return document.getElementById(idName);
}
function qs(selector) {
return document.querySelector(selector);
}
function qsa(selector) {
return document.querySelectorAll(selector);
}
function gen(elType) {
return document.createElement(elType);
}
CSE 154 JS Cheat Sheet Summer 2019 - Version 06/23/19
Accessing DOM elements from the document
These are methods/properties than can be accessed from the global documentobject, for example:
document.getElementById(“my-btn”);
Method/Property and Example Description
getElementById
(idName
) Returns a DOM object whose id property matches the
specified string. If no matches are found, null is
getElementById(“my-btn”);
returned.
(s
querySelectorAll elector) Returns a list of the document’s elements that match
the specified group of selectors. If no matches are
querySelectorAll(“li.highlighted”);
found, null is returned.
querySelectorselector
( ) Returns the first DOM element that matches the
specified selector, or group of selectors. If no matches
querySelector(“li.highlighted”);
are found, null is returned.
DOM Element .classList Methods
Method Description
el.classList.add
(class) Adds specified class values. These values are
div.classList.add(“skittle”) ignored if they already exist in the list.
div.classList.add(“skittle”, “green”);
el.
classList.remove
(class) Removes the specified class value
div.classList.remove(“green”);
el.
classList.toggle
(class) Toggles the listed class value. If the class
div.classList.toggle(“hidden”); exists, then removes it and returns false, if it did
not exist in the list add it and return true
el
.classList.contains
(class) Returns true if the specified class value is exists
div.classList.contains(“highlighted”); in the classList for this element
CSE 154 JS Cheat Sheet Summer 2019 - Version 06/23/19
DOM Element Methods and Properties
Recall that if you have an HTML element on your page that has attributes, you can set those properties through
JavaScript as well. For instance if your
<img id="dog-tag" src="img/doggie.jpg" alt="My Cute Dog" />
Your could do the following in your JavaScript code (using the idalias for document.getElementById):
id("dog-tag").alt = "My really cute dog";
Example DOM Element attributes include (other than src, and alt a
bove) are:
Property Description
el.
disabled Whether or not the DOM element (e.g. a button or input) is disabled
el.
value The value attribute of form elements (input, textarea, c heckboxradio,
, etc.)
select
el.
id The id attribute of an element
el.
textContent Sets or returns the text content of the specified node
el.
innerHTML Sets or returns the HTML content of an element
el. (a
getAttribute ttr
) Returns the specified attribute value attr of el
el.
children Returns a collection of the child elements of el
el.
parentNode Returns the parent node of el
el.
classList Returns the class name(s) of el
el.
className Sets or returns the value of the class attribute of el
CSE 154 JS Cheat Sheet Summer 2019 - Version 06/23/19
DOM Manipulation Methods
Method/Property and Example Description
document (t
.createElement agname
) Creates and returns an Element node. Note that this
method is used on document not a DOM node.
let li = document.createElement(“li”);
el. (c
appendChild hild
) Adds a new child node to el as the last child node
ol.appendChild(li);
el. (c
removeChild hild
) Removes a child node from an element
ol.removeChild(li);
el. (n
insertBefore ewNode refNode
, ); Adds newNode to parent elbefore el’s child refNode
position
ol.insertBefore(newLi, existingLi);
DOM and Events
DOM Method/Property Description
el. (e
addEventListener vent fn
, ) Attaches an event handler function fn to the
specified element el to listen to event
el. (e
removeEventListener vent
, f
n
) Removes the event handler fnto the specified e l
listening to event
Event Types
click mousemove keydown change
dblclick mouseout error focus
mouseenter mouseover success submit
mouseleave mouseup load select
mousedown keyup unload resize
CSE 154 JS Cheat Sheet Summer 2019 - Version 06/23/19
Useful Event Object Methods and Properties
Any function assigned in an addEventListener can accept an optional argument, which will be the Event
object. These are some things you can do with that object.
function init() {
id(“my-btn”).addEventListener(“click”, handleClick);
}
function handleClick(evt) {
console.log(evt.target); // #my-btn
}
Method Description
evt.target Returns the element that triggered the event
evt.type Returns the name of the event
offsetX Returns the horizontal coordinate of the mouse pointer, relative to the DOM
element clicked
offsetY Returns the vertical coordinate of the mouse pointer, relative to the DOM element
clicked
timestamp Timestamp (in ms) the event object was created.
JavaScript string Methods and Properties
Method Description
length Returns the length of a string
charAt(index) Returns the character at the specified index
indexOf(string) Returns the position of the first found occurrence of a specified value in a
string
split(delimiter) Splits a string at instances of the delimiter into an array of substrings
substring(start, end) Extracts the characters from a string between two specified indices
trim() Removes whitespace from both ends of a string
toLowerCase() Returns a lowercase version of a string
toUpperCase() Returns an uppercase version of a string
CSE 154 JS Cheat Sheet Summer 2019 - Version 06/23/19
JavaScript Array Methods and Properties
Method Description
length Sets or returns the number of elements in an array
push(el) Adds new elements to the end of an array and returns the new length
pop() Removes and returns the last element of an array
unshift(el) Adds new elements to the beginning of an array and returns the new length
shift() Removes and returns the first element in an array
sort() Sorts the elements of an array
join() Returns a string concatenating all elements of an array (maintaining order)
indexOf(el) Returns the index of the element in the array, or -1 if not found
JavaScript Math Functions
Method Description
Math.random() Returns a double between 0 (inclusive) and 1 (exclusive)
Math.abs(n) Returns the absolute value of n
Math.min(a, b, ...) Returns the smallest of 0 or more numbers
Math.max(a, b, ...) Returns the largest of 0 or more numbers
Math.round(n) Returns the value of n rounded to the nearest integer
Math.ceil(n) Returns the smallest integer greater than or equal to n
Math.floor(n) Returns the largest integer less than or equal to n
Math.pow(n, e) ower, that is, ne
Returns the base n to the exponent e p
CSE 154 JS Cheat Sheet Summer 2019 - Version 06/23/19