Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.
Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.
Frontend environments evolve rapidly nowadays and modern browsers have already implemented a great deal of DOM/BOM APIs which are good enough for production use. We don't have to learn jQuery from scratch for DOM manipulation or event handling. In the meantime, thanks to the spread of frontend libraries such as React, Angular and Vue, manipulating the DOM directly becomes anti-pattern, so that jQuery usage has never been less important. This project summarizes most of the alternatives in native Javascript implementation to jQuery methods, with IE 10+ support.
ℹ️ Notice:
In place of common selectors like class, id or attribute we can use document.querySelector or document.querySelectorAll for substitution. The differences lie in:
document.querySelector returns the first matched elementdocument.querySelectorAll returns all matched elements as NodeList. It can be converted to Array using Array.prototype.slice.call(document.querySelectorAll(selector)); or any of the methods outlined in makeArraydocument.querySelectorAll will return [], whereas document.querySelector will return null.Notice:
document.querySelectoranddocument.querySelectorAllare quite SLOW, thus try to usedocument.getElementById,document.getElementsByClassNameordocument.getElementsByTagNameif you want to get a performance bonus.
1.0 Query by selector
// jQuery
$('selector');
// Native
document.querySelectorAll('selector');
1.1 Query by class
// jQuery
$('.class');
// Native
document.querySelectorAll('.class');
// or
document.getElementsByClassName('class');
1.2 Query by id
// jQuery
$('#id');
// Native
document.querySelector('#id');
// or
document.getElementById('id');
// or
window['id']
1.3 Query by attribute
// jQuery
$('a[target=_blank]');
// Native
document.querySelectorAll('a[target=_blank]');
1.4 Query in descendants
// jQuery
$el.find('li');
// Native
el.querySelectorAll('li');
1.5 Sibling/Previous/Next Elements
All siblings
// jQuery
$el.siblings();
// Native - latest, Edge13+
[...el.parentNode.children].filter((child) =>
child !== el
);
// Native (alternative) - latest, Edge13+
Array.from(el.parentNode.children).filter((child) =>
child !== el
);
// Native - IE10+
Array.prototype.filter.call(el.parentNode.children, (child) =>
child !== el
);
Previous sibling
// jQuery
$el.prev();
// Native
el.previousElementSibling;
Next sibling
// jQuery
$el.next();
// Native
el.nextElementSibling;
All previous siblings
// jQuery (optional filter selector)
$el.prevAll($filter);
// Native (optional filter function)
function getPreviousSiblings(elem, filter) {
var sibs = [];
while (elem = elem.previousSibling) {
if (elem.nodeType === 3) continue; // ignore text nodes
if (!filter || filter(elem)) sibs.push(elem);
}
return sibs;
}
All next siblings
…
js function exampleFilter(elem) { switch (elem.nodeName.toUpperCase()) { case 'DIV': return true; case 'SPAN': return true; default: return false; } }
- [1.6](#1.6) <a name='1.6'></a> Closest
Return the first matched element by provided selector, traversing from current element up through its ancestors in the DOM tree.
```js
// jQuery
$el.closest(selector);
// Native - Only latest, NO IE
el.closest(selector);
// Native - IE10+
function closest(el, selector) {
const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
while (el) {
if (matchesSelector.call(el, selector)) {
return el;
} else {
el = el.parentElement;
}
}
return null;
}
1.7 Parents Until
Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.
// jQuery
$el.parentsUntil(selector, filter);
// Native
function parentsUntil(el, selector, filter) {
const result = [];
const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
// match start from parent
el = el.parentElement;
while (el && !matchesSelector.call(el, selector)) {
if (!filter) {
result.push(el);
} else {
if (matchesSelector.call(el, filter)) {
result.push(el);
}
}
el = el.parentElement;
}
return result;
}
1.8 Form
Input/Textarea
// jQuery
$('#my-input').val();
// Native
document.querySelector('#my-input').value;
Get index of e.currentTarget between .radio
// jQuery
$('.radio').index(e.currentTarget);
// Native
Array.from(document.querySelectorAll('.radio')).indexOf(e.currentTarget);
or
Array.prototype.indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
1.9 Iframe Contents
$('iframe').contents() returns contentDocument for this specific iframe
Iframe contents
// jQuery
$iframe.contents();
// Native
iframe.contentDocument;
Iframe Query
// jQuery
$iframe.contents().find('.css');
// Native
iframe.contentDocument.querySelectorAll('.css');
1.10 Get body
// jQuery
$('body');
// Native
document.body;
1.11 Attribute getter and setter
Get an attribute
// jQuery
$el.attr('foo');
// Native
el.getAttribute('foo');
Set an attribute
// jQuery
$el.attr('foo', 'bar');
// Native
el.setAttribute('foo', 'bar');
Get a data- attribute
// jQuery
$el.data('foo');
// Native (use `getAttribute`)
el.getAttribute('data-foo');
// Native (use `dataset` if only need to support IE 11+)
el.dataset['foo'];
1.12 Selector containing string (case-sensitive)
// jQuery
$("selector:contains('text')");
// Native
function contains(selector, text) {
var elements = document.querySelectorAll(selector);
return Array.from(elements).filter(function(element) {
return RegExp(text).test(element.textContent);
});
}
2.1 CSS
Get style
// jQuery
$el.css('color');
// Native
// NOTE: Known bug, will return 'auto' if style value is 'auto'
const win = el.ownerDocument.defaultView;
// null means not to return pseudo styles
win.getComputedStyle(el, null).color;
Set style
// jQuery
$el.css({ color: '#f01' });
// Native
el.style.color = '#f01';
Get/Set Styles
// jQuery
$el.css({ color: '#f01', 'border-color': '#f02' })
// Native
Object.assign(el.style, { color: '#f01', borderColor: '#f02' })
Add class
// jQuery
$el.addClass(className);
// Native
el.classList.add(className);
Remove class
// jQuery
$el.removeClass(className);
// Native
el.classList.remove(className);
has class
// jQuery
$el.hasClass(className);
// Native
el.classList.contains(className);
Toggle class
// jQuery
$el.toggleClass(className);
// Native
el.classList.toggle(className);
2.2 Width & Height
Width and Height are theoretically identical, take Height as example:
Window height
// window height
$(window).height();
// without scrollbar, behaves like jQuery
window.document.documentElement.clientHeight;
// with scrollbar
window.innerHeight;
Document height
// jQuery
$(document).height();
// Native
const body = document.body;
const html = document.documentElement;
const height = Math.max(
body.offsetHeight,
body.scrollHeight,
html.clientHeight,
html.offsetHeight,
html.scrollHeight
);
Element height
// jQuery
$el.height();
// Native
function getHeight(el) {
const styles = window.getComputedStyle(el);
const height = el.offsetHeight;
const borderTopWidth = parseFloat(styles.borderTopWidth);
const borderBottomWidth = parseFloat(styles.borderBottomWidth);
const paddingTop = parseFloat(styles.paddingTop);
const paddingBottom = parseFloat(styles.paddingBottom);
return height - borderBottomWidth - borderTopWidth - paddingTop - paddingBottom;
}
// accurate to integer(when `border-box`, it's `height - border`; when `content-box`, it's `height + padding`)
el.clientHeight;
// accurate to decimal(when `border-box`, it's `height`; when `content-box`, it's `height + padding + border`)
el.getBoundingClientRect().height;
2.3 Position & Offset
Position
Get the current coordinates of the element relative to the offset parent.
// jQuery
$el.position();
// Native
{ left: el.offsetLeft, top: el.offsetTop }
Offset
Get the current coordinates of the element relative to the document.
// jQuery
$el.offset();
// Native
function getOffset (el) {
const box = el.getBoundingClientRect();
return {
top: box.top + window.pageYOffset - document.documentElement.clientTop,
left: box.left + window.pageXOffset - document.documentElement.clientLeft
};
}
2.4 Scroll Top
Get the current vertical position of the scroll bar for the element.
// jQuery
$(window).scrollTop();
// Native
(document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
3.1 Remove
Remove the element from the DOM.
// jQuer