Javascript for the DOM Cheatsheet

Functions, tips and tricks to manipulate the DOM with Javascript
Tags : html javascript js html5

Query the DOM
// Get by ID
let el = document.getElementById("element_id");

// Get by query string
const myClass = document.querySelector(".classname");
const myInput = document.querySelector(".classname input[name='identifiant']");

// Find in specific element
const parentEl = document.querySelector(".parent");
parentEl.querySelector(".child").innerHTML = "child text";
Create element
let divEl = document.createElement("div");

let textNode = document.createTextNode("Hello World!");

divEl.appendChild(textNode);
Edit an element
// Get content
let content = myElement.innerHTML;

// Set content
let myEl.innerHTML = "content text";
Event declaration
let buttonEl = document.querySelector(".btn");
buttonEl.addEventListener("mousedown", e => { ... });
Event common event types
// Mouse
click, mouseup, mousedown
// Keyboard
keydown, keyup
// Forms
focus, blur, change, submit
// Window
scroll, resize, load
// Touch
touchstart, touchend, touchmove, touchcancel
Component example
class CustomList extends HTMLUListElement {
    constructor() {
        super();
        // ...
    }
}

// Define
customElements.define('custom-list', CustomList, { extends: 'ul' });
let customList = document.createElement('ul', { is : 'custom-list' })