Essential JavaScript DOM API Cheat Sheet: From Element Selection to Ajax
This article provides a comprehensive, English‑language reference of common JavaScript DOM APIs—including element selection, class manipulation, node operations, attribute handling, content updates, CSS styling, size calculations, event binding, DOM ready detection, context binding, whitespace trimming, Ajax requests, JSON parsing, and node traversal—complete with code examples for each feature.
Below is a compiled list of commonly used JavaScript APIs covering element selection, class manipulation, node operations, attribute handling, content manipulation, CSS styling, size and position, events, DOM ready, context binding, whitespace trimming, Ajax requests, JSON handling, and node traversal.
Element Search
Class Operations
Node Operations
Attribute Operations
Content Operations
CSS Operations
Position and Size
Events
DOM Ready
Binding Context
Trim Whitespace
Ajax
JSON Handling
Node Traversal
Element Search
// Node
document.getElementById(id) // document.getElementById('test')
document.querySelector(selectors) // document.querySelector('#test div')
document.doctype
document.documentElement
document.head
document.title
document.body
// NodeList
document.getElementsByClassName(names) // document.getElementsByClassName('test')
document.getElementsByName(name) // document.getElementsByName('demo')
document.getElementsByTagName(name) // document.getElementsByTagName('div')
document.getElementsByTagNameNS(namespace, name) // document.getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'div')
document.querySelectorAll(selectors) // document.querySelectorAll('#test div')
document.links
document.scripts
document.images
document.embeds
document.formsClass Operations
// IE8 – add class
el.className += ' ' + className;
// has class (IE8)
function hasClass(el, className){
return new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
}
// toggle class (IE8)
function toggleClass(el, className){
var classes = el.className.split(' ');
var existingIndex = -1;
for(var i = classes.length; i--;){
if(classes[i] === className){
existingIndex = i;
}
}
if(existingIndex >= 0){
classes.splice(existingIndex, 1);
} else {
classes.push(className);
}
el.className = classes.join(' ');
}
// remove class (IE8)
function remove(el, className){
el.className = el.className.replace(new RegExp('(^|\b)' + className.split(' ').join('|') + '(\b|$)', 'gi'), ' ');
}
// IE10+ – use classList
el.classList.add(className); // add class
el.classList.remove(className); // remove class
el.classList.contains(className); // has class
el.classList.toggle(className); // toggle classNode Operations
// Create
var el = document.createElement(name);
// Clone (true clones children and attributes)
el.cloneNode(true);
// Append as last child
parent.appendChild(el);
// Insert before a specific child (first child in this example)
parent.insertBefore(el, parent.childNodes[0]);
// insertAdjacentHTML variations
el.insertAdjacentHTML('beforeBegin', htmlString); // before element
el.insertAdjacentHTML('afterBegin', htmlString); // as first child
el.insertAdjacentHTML('beforeEnd', htmlString); // as last child
el.insertAdjacentHTML('afterEnd', htmlString); // after element
// Parent node
el.parentNode;
// Remove node
el.parentNode.removeChild(el);
// Siblings (IE9+)
var siblings = Array.prototype.filter.call(el.parentNode.children, function(child){
return child !== el;
});
// Next sibling (IE8)
function nextElementSibling(el){
do { el = el.nextSibling; } while (el && el.nodeType !== 1);
return el;
}
nextElementSibling(el);
// Previous sibling (IE8)
function previousElementSibling(el){
do { el = el.previousSibling; } while (el && el.nodeType !== 1);
return el;
}
previousElementSibling(el);
// Children (IE8)
var children = [];
for(var i = el.children.length; i--;){
if(el.children[i].nodeType != 8) children.unshift(el.children[i]);
}
// IE9+
el.children;Attribute Operations
// Get attribute value
el.getAttribute('alt');
// Set attribute value
el.setAttribute('alt', 'Image description');Content Operations
// Get element content
el.innerHTML;
// Set element content
el.innerHTML = string;
// Get outer HTML (including the element itself)
el.outerHTML;
// Set outer HTML
el.outerHTML = string;
// Get text content (IE8)
el.innerText;
// Get text content (IE9+)
el.textContent;
// Set text content (IE8)
el.innerText = string;
// Set text content (IE9+)
el.textContent = string;CSS Operations
// Get computed style (IE8)
el.currentStyle[attrName];
// Get computed style (IE9+)
window.getComputedStyle(el)[attrName];
// Get pseudo‑element style
window.getComputedStyle(el, ':after')[attrName];
// Set CSS style
el.style.display = 'none';Position and Size
// getBoundingClientRect returns top, left, right, bottom, width, height
var rect = el.getBoundingClientRect();
return {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
};
// Element's own width/height (including border & padding)
el.offsetWidth;
el.offsetHeight;
// Offset from parent
el.offsetLeft;
el.offsetTop;
// Viewport size (IE9+)
var pageWidth = window.innerWidth,
pageHeight = window.innerHeight;
if (typeof pageWidth != "number") {
if (document.compatMode == "CSS1Compat") {
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
}Events
// Bind event (IE9+)
el.addEventListener(eventName, handler, false); // false = bubble, true = capture
// Bind event (IE8)
el.attachEvent('on' + eventName, function(){ handler.call(el); });
// Remove event (IE9+)
el.removeEventListener(eventName, handler);
// Remove event (IE8)
el.detachEvent('on' + eventName, handler);
// Trigger event (IE9+)
if (document.createEvent) {
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);
} else { // IE8
el.fireEvent('onchange');
}
// Event object
var event = window.event || event;
var target = event.target || event.srcElement;
// Event delegation example
ul.addEventListener('click', function(event){
if (event.target.tagName.toLowerCase() === 'li') {
console.log(event.target.innerHTML);
}
});DOM Ready
function ready(fn){
if (document.readyState != 'loading') {
// IE9+
document.addEventListener('DOMContentLoaded', fn);
} else {
// IE8
document.attachEvent('onreadystatechange', function(){
if (document.readyState != 'loading') {
fn();
}
});
}
}Binding Context
// IE8
fn.apply(context, arguments);
// IE9+
fn.bind(context);Trim Whitespace
// IE8
string.replace(/^\s+|\s+$/g, '');
// IE9+
string.trim();Ajax
// GET (asynchronous)
var request = new XMLHttpRequest();
request.open('GET', 'user.php?fname=Bill&lname=Gates', true);
request.send();
// IE8 – handle state change
request.onreadystatechange = function(){
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.responseText);
} else {
// error handling
}
}
};
// IE9+ – onload / onerror
request.onload = function(){
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
} else {
// server returned error
}
};
request.onerror = function(){
// connection error
};
// POST
var request = new XMLHttpRequest();
request.open('POST', 'user.php', true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send(dataString);JSON Handling
JSON.parse(string);
JSON.stringify(Object);Node Traversal
function forEach(nodeList, callback){
if (Array.prototype.forEach) {
// IE9+
Array.prototype.forEach.call(nodeList, callback);
} else {
// IE8
for (var i = 0; i < nodeList.length; i++) {
callback(nodeList[i], i);
}
}
}
forEach(document.querySelectorAll(selector), function(el, i){
// your code here
});Feel free to add more.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
