Plain Javascript Cheatsheet/js (without jQuery)

Jquery Document Ready Equivalent

  • document.addEventListener("DOMContentLoaded", function(event) { 
      ...
    });

Variables

Check if variable exists / is defined

  • if (typeof myVar !== 'undefined') {
      myVar.doSomething();
    }
    

Properties

element.nodeName
element.outerHTML
element.innerText
<div data-country="US"></div
element.dataset.country;

 

Selectors

Document / Body

document.documentElement // = <html>
document.body

Find By

const element = document.getElementById('#myDiv');
const uls = doc.getElementsByTagName('ul');

Iterate

const uls = doc.getElementsByTagName('ul');
if (uls.length) {
    for (let ul of uls) {
      console.log(ul);
    }
}

Parent

const parent = element.parentElement;

// Find parent element by selector
const parent = element.closest('form');

Child

const span = element.querySelector('span');

 

Get multiple elements and iterate:

const submenues = this.navbarUlTarget.querySelectorAll('ul');
submenues.forEach( element => {
    element.classList.remove('show');
});

CSS Classes

const hasClass = element.classList.contains('show');

element.classList.add('show');

element.classList.remove('show');

element.classList.toggle("show");

DOM Manipulating:

  • // Replace element content:
    element.innerHTML = 'foo';
  • // Append to element content:
    element.insertAdjacentHTML('beforeend', 'foo');

Create DOM from string

  • const doc = new DOMParser().parseFromString('<html><body<h1>foo</h2></body></html>','text/html');

When document is ready

  • document.addEventListener("DOMContentLoaded", function(event) { 
      //do work
    });

Scrolling

  • element.scrollIntoView();

Timeout / Interval

  • setTimeout(() => {  
        console.log("World!");
    }, 5000);

Wait until an object exists and a property is true

// We are inside an object method:
const checkExist = setInterval(function (object) {
    // object is the current object/class, now let's try to get another object
    const someObject = object.getSomeObject();

    if (someObject && someObject.isHappy) {
        clearInterval(checkExist);
        someObject.jumpInTheAir();
    } else {
        console.log('Waiting...');
    }

}, 500, this /*give the current object as parameter to setInterval*/);

Events

Stop default action (e.g. load a href target)

event.preventDefault();
event.stopImmediatePropagation();

Get event element

toggle(event) {
        // Get the clicked element:
        var button = event.currentTarget;
        // or 
        var button = event.target;

}

Dispatch (=create/trigger) an event:

const customEvent = new CustomEvent(
    'my-namespace:my-event-name',
    { detail: { myAdditionalData: 'foo }}
);
window.dispatchEvent(customEvent);

Listen (=connect) to an event:

window.addEventListener('my-namespace:my-event-name', function(event) {
  console.log(event.detail.myAdditionalData;
});

 

Forms

FormData

  • const formData = new FormData(formElement);
    formData.set('first_name', 'Klemens');
    
  • const url = '/myurl/' + '?' + new URLSearchParams(new FormData(formElement));

Submit a form via ajax

And replace the form HTML with the response HTML

  • async submit(event) {
      event.preventDefault();
      event.stopImmediatePropagation();
    
      const form = document.getElementById('myForm');
    
      const url = form.action;
      const data = new FormData(form)
    
      const response = await fetch(url, {
        method: 'post',
         body: data,
      });
    
      const html = await response.text();
      form.outerHTML = html;
    }
    

Checkbox

Set a value

  • formField.value = 69;

Check a checkbox

  • checkbox.checked = true; // false