Hello World

吞风吻雨葬落日 欺山赶海踏雪径

0%

原生js替代JQuery

vanilla-js-dom 的使用教程 :)

https://github.com/Haeresis/vanilla-js-dom/blob/master/README.md

github地址:
https://github.com/Haeresis/vanilla-js-dom

Vanilla JS

其实你什么框架都不需要!

Overview

Vanilla JS is a fast, lightweight, cross-platform tool for building incredible, powerful JavaScript applications.

Use in Development

Just put the following code:

1
<!-- <script src="path/to/vanilla.js"></script> -->

Use in Production

The much faster method:

1
 

Speed Comparison

When Vanilla JS perform 100 operations, others do:

Retrieve DOM element by ID

Code 100 ops Vanilla JS
Vanilla JS document.getElementById(‘vanilla’); 100
Dojo dojo.byId(‘dojo’); 92
Prototype JS $(‘prototype’); 57
jQuery $(‘#jquery’); 42
MooTools document.id(‘mootools’); 24

Retrieve 10 DOM elements by tag name

Code 100 ops Vanilla JS
Vanilla JS document.getElementsByTagName(‘div’); 100
Prototype JS Prototype.Selector.select(‘div’, document); 25
jQuery $(‘div’); 21
Dojo dojo.query(‘div’); 3
MooTools Slick.search(document, ‘div’, new Elements); 2

Vanilla JS vs jQuery

Retrieve 10 DOM elements by class name

Code 100 ops Vanilla JS
Vanilla JS document.getElementsByClassName(‘vanilla’); 100
jQuery $(‘.jquery’); 25

Retrieve DOM element with <#id> .inner span selector

Code 100 ops Vanilla JS
Vanilla JS document.querySelector(‘#vanilla .inner span’); 100
jQuery $(‘#jquery .inner span’); 17

Retrieve 10 DOM elements with <.className> .inner span selector

Code 100 ops Vanilla JS
Vanilla JS document.querySelectorAll(‘.vanilla .inner span’); 100
jQuery $(‘.jquery .inner span’); 51

Vanilla JS Selector Performances

All tests are based on <section id="vanilla" class="vanilla"><article class="inner"><div class="target" id="target"></div></article></section> HTML.

Select node <div class="target" id="target"></div> 100 ops Vanilla JS
document.getElementsByTagName(‘div’); 100
document.getElementById(‘target’); 99
document.getElementsByClassName(‘target’); 96
document.querySelector(‘.vanilla .inner div’); 68
document.querySelectorAll(‘.vanilla .inner div’); 35

From jQuery to Vanilla JS

Legend

Understand each type of DOM Object:

1
2
3
4
5
6
<div class="example">
<span>(Text into) Html Element</span>
<!-- Comment Element -->
Text Element
<span>(Text into) Html Element</span>
</div>
  • querySelector('.example') return a HTMLElement.
  • querySelector('.example').children return a HTMLCollection, each collection’s item is a HTMLElement, two [span, span] here.
  • querySelector('.example').childNodes return a NodeList, each collection’s item is a Node, seven [text, span, text, comment, text, span, text] here.
  • querySelector('.example').childNodes[0] return a Text (Node) of typeNode 3, as a text. (...nodeList[3] is typeNode 8 as a Comment (Node too)).

.Node #Selector

#id

From jQuery

1
var htmlElement = $('#id')[0];

to Vanilla JS

1
var htmlElement = document.getElementById('id');

.classname #id tagname

From jQuery

1
var htmlElement = $('#id .classname tagname')[0];

to Vanilla JS

1
document.querySelector('#id .classname tagname');

[.classname #id tagname]

From jQuery

1
2
3
$('#id .classname tagname').each(function (i, htmlElement) {
htmlElement;
});

to Vanilla JS

1
2
3
4
var nodeList = document.querySelectorAll('#id .classname tagname'); // Not Live (Snapshot)
[].forEach.call(nodeList, function (node) {
node;
});

[.classname]

From jQuery

1
2
3
$('.classname').each(function (i, htmlElement) {
htmlElement;
});

to Vanilla JS

1
2
3
4
5
var htmlCollection = document.getElementsByClassName('classname'); // Live
// var nodeList = document.querySelectorAll('.classname'); // Not Live (Snapshot)
[].forEach.call(htmlCollection, function (htmlElement) {
htmlElement;
});

[name]

From jQuery

1
2
3
$('[name="name"]').each(function (i, htmlElement) {
htmlElement;
});

to Vanilla JS

1
2
3
4
5
var nodeList = document.getElementsByName('name'); // Live
// var nodeList = document.querySelectorAll('[name=name]'); // Not Live (Snapshot)
[].forEach.call(nodeList, function (node) {
node;
});

[tagname]

From jQuery

1
2
3
$('tagname').each(function (i, htmlElement) {
htmlElement;
});

to Vanilla JS

1
2
3
4
5
var htmlCollection = document.getElementsByTagName('tagname'); // Live
// var nodeList = document.querySelectorAll('tagname'); // Not Live (Snapshot)
[].forEach.call(htmlCollection, function (htmlElement) {
htmlElement;
});

Reverted Loop

From jQuery

1
2
3
$($('.className').get().reverse()).each(function (i, htmlElement) {
htmlElement;
});

to Vanilla JS

1
2
3
4
5
var htmlCollection = document.getElementsByClassName('className'), // Live
i = htmlCollection.length;
while (htmlElement = htmlCollection[--i]) {
htmlElement;
}

AJAX

GET

From jQuery

1
2
3
4
5
$.ajax({
type: 'GET',
url: <url>,
data: <data>
});

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
fetch(<url>, {
method: 'GET',
body: <data>
});

/*
var get = new XMLHttpRequest();
get.open('GET', <url>, true);
get.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
get.send(<data>);
*/

JSON

From jQuery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}

throw new Error('There was a connection error of some sort.');
}
fetch(<url>)
.then(checkStatus)
.then(response => response.json())
.catch(error => error);

/*
function getJSON(url, next) {
$.getJSON(url, function (data) {
next(null, data);
}).error(function () {
next(new Error('There was a connection error of some sort.'));
});
}

getJSON(<url>, function (err, data) {
if (err) {
return err;
}

data;
});
*/

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function getJSON(url, next) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.send();

request.addEventListener('load', function () {
if (request.status < 200 && request.status >= 400) {
return next(new Error('We reached our target server, but it returned an error.'));
}

next(null, JSON.parse(request.responseText));
});

request.addEventListener('error', function () {
next(new Error('There was a connection error of some sort.'));
});
}

getJSON(<url>, function (err, data) {
if (err) {
return err;
}

data;
});

POST

From jQuery

1
2
3
4
5
$.ajax({
type: 'POST',
url: <url>,
data: <data>
});

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
12
fetch(<url>, {
method: 'POST',
body: <data>
});

/*
// IE fallback
var post = new XMLHttpRequest();
post.open('POST', <url>, true);
post.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
post.send(<data>);
*/

Request / Response

From jQuery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}

throw new Error('There was a connection error of some sort.');
}

fetch(<url>)
.then(checkStatus)
.then(response => response)
.catch(error => error);

/*
function request(url, next) {
$.ajax({
type: 'GET',
url: url,
success: function(response) {
next(null, response);
},
error: function() {
next(new Error('There was a connection error of some sort.'));
}
});
}

request(<url>, function (err, response) {
if (err) {
return err;
}

response;
});
*/

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function request(url, next) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.send();

request.addEventListener('load', function () {
if (request.status < 200 && request.status >= 400) {
return next(new Error('We reached our target server, but it returned an error.'));
}

next(null, request.responseText);
});

request.addEventListener('error', function () {
return next(new Error('There was a connection error of some sort.'));
});
}

request(<url>, function (err, response) {
if (err) {
return err;
}

response;
});

ATTRIBUTS

Add Class

From jQuery

1
$(<htmlElement>).addClass(<className>);

to Vanilla JS

1
<htmlElement>.classList.add(<className>);

Get Attribute

From jQuery

1
$(<htmlElement>).attr(<attributeName>);

to Vanilla JS

1
<htmlElement>.getAttribute(<attributeName>);

Get Data

From jQuery

1
$(<htmlElement>).data(<dataName>);

to Vanilla JS

1
<htmlElement>.getAttribute('data-' + <dataName>);

Get Value

From jQuery

1
$(<htmlElement>).val();

to Vanilla JS

1
<htmlElement>.value;

Has Class

From jQuery

1
$(<htmlElement>).hasClass(<className>);

to Vanilla JS

1
<htmlElement>.classList.contains(<className>);

Remove Attribute

From jQuery

1
$(<htmlElement>).removeAttr(<attributeName>);

to Vanilla JS

1
<htmlElement>.removeAttribute(<attributeName>);

Remove Class

From jQuery

1
$(<htmlElement>).removeClass(<className>);

to Vanilla JS

1
<htmlElement>.classList.remove(<className>);

Remove Data

From jQuery

1
$(<htmlElement>).removeData(<dataName>);

to Vanilla JS

1
<htmlElement>.removeAttribute('data-' + <dataName>);

Set Attribute

From jQuery

1
$(<htmlElement>).attr(<attributeName>, <value>);

to Vanilla JS

1
<htmlElement>.setAttribute(<attributeName>, <value>);

Set Data

From jQuery

1
$(<htmlElement>).data(<dataName>, <value>);

to Vanilla JS

1
<htmlElement>.setAttribute('data-' + <dataName>, <value>);

Set Value

From jQuery

1
$(<htmlElement>).val(<value>);

to Vanilla JS

1
<htmlElement>.value = <value>;

Toggle Class

From jQuery

1
$(<htmlElement>).toggleClass(<className>);

to Vanilla JS

1
<htmlElement>.classList.toggle(<className>);

EFFECTS

Animation

From jQuery

1
2
3
4
5
6
function fadeIn($htmlElement, speed, next) {
$htmlElement.css('opacity', '0').animate({ opacity: 1 }, speed, next);
}
fadeIn($(<htmlElement>), 2000, function () {
$(this).css('opacity', '');
});

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function fadeIn(htmlElement, speed, next) {
var last = +new Date(),
tick = function () {
htmlElement.style.opacity = +htmlElement.style.opacity + (new Date() - last) / speed;

last = +new Date();

if (+htmlElement.style.opacity < 1) {
requestAnimationFrame(tick);
} else if (next) {
next.call(htmlElement);
}
};

htmlElement.style.opacity = 0;
tick();
}

fadeIn(<htmlElement>, 2000, function () {
this.style.opacity = '';
});

Hide

From jQuery

1
$(<htmlElement>).hide();

to Vanilla JS

1
<htmlElement>.style.display = 'none';

Show

From jQuery

1
$(<htmlElement>).show();

to Vanilla JS

1
<htmlElement>.style.display = '';

EVENTS

Hover

From jQuery

1
$(<htmlElement>).hover(<eventHandlerMouseIn>, <eventHandlerMouseOut>);

to Vanilla JS

1
2
<htmlElement>.addEventListener('mouseenter', <eventHandlerMouseIn>);
<htmlElement>.addEventListener('mouseleave', <eventHandlerMouseOut>);

Load

From jQuery

1
2
3
$(<htmlElement>).load(function () {
// I am full loaded.
});

to Vanilla JS

1
2
3
<htmlElement>.addEventListener('load', function () {
// I am full loaded.
});

Off

From jQuery

1
$(<htmlElement>).off(<eventName>, <eventHandler>);

to Vanilla JS

1
<htmlElement>.removeEventListener(<eventName>, <eventHandler>);

On

From jQuery

1
$(<htmlElement>).on(<eventName>, <eventHandler>);

to Vanilla JS

1
<htmlElement>.addEventListener(<eventName>, <eventHandler>);

One

From jQuery

1
$(<htmlElement>).one(<eventName>, <eventHandler>);

to Vanilla JS

1
2
3
4
5
6
<htmlElement>.addEventListener(<eventName>,<eventHandler>,{once: true});
/*
<htmlElement>.addEventListener(<eventName>, function callee(event) {
event.target.removeEventListener(e.type, callee);
});
*/

Ready

From jQuery

1
2
3
$(document).ready(function () {
// I am ready to be manipulate.
});

to Vanilla JS

1
2
3
document.addEventListener('DOMContentLoaded', function () {
// I am ready to be manipulate.
});

Trigger

From jQuery

1
2
3
4
5
6
7
8
var event = jQuery.Event('click');
event.test = true;

$(<htmlElement>).click(function (event) {
event.test; // undefined by click, true by trigger.
});
$(<htmlElement>).trigger(event);
// $(<htmlElement>).trigger('click'); // Shortcut without test property.

to Vanilla JS

1
2
3
4
5
6
7
var event = new Event('click');
event.test = true;

<htmlElement>.addEventListener('click', function (event) {
event.test; // undefined by click, true by trigger.
});
<htmlElement>.dispatchEvent(event);

FILTERS

Filter

From jQuery

filterCondition

1
2
3
4
5
$(<selector>).filter(function (i, htmlElement) {
return <filterCondition>;
}).each(function (i, htmlElement) {
htmlElement;
});

to Vanilla JS

1
2
3
4
5
6
7
8
9
var nodeList = document.querySelectorAll(<selector>);

nodeList = [].filter.call(nodeList, function (node) {
return <filterCondition>;
});

[].forEach.call(nodeList, function (node) {
node;
});

First

From jQuery

1
$(<selector>).first();

to Vanilla JS

1
2
<htmlCollection>.item(0);
// <htmlCollection>[0];

Has

From jQuery

1
$(<selector>).has(<matchesChildSelector>);

to Vanilla JS

1
2
3
4
var nodeList = document.querySelectorAll(<selector>);
[].filter.call(nodeList, function (node) {
return node.querySelector(<matchesChildSelector>);
});

Is

From jQuery

1
$(<selector>).is(<matchesSelector>);

to Vanilla JS

1
2
3
4
var nodeList = document.querySelectorAll(<selector>);
[].some.call(nodeList, function (node) {
return node.matches(<matchesSelector>);
});

Item

From jQuery

1
$(<selector>).eq(<index>);

to Vanilla JS

1
2
<htmlCollection>.item(<index>);
// <htmlCollection>[<index>];

Last

From jQuery

1
$(<selector>).last();

to Vanilla JS

1
2
<htmlCollection>.item(<htmlCollection>.length - 1);
// <htmlCollection>[<htmlCollection>.length - 1];

Not

From jQuery

1
$(<selector>).not(<matchesSelector>);

to Vanilla JS

1
2
3
4
var nodeList = document.querySelectorAll(<selector>);
[].filter.call(nodeList, function (node) {
return !node.matches(<matchesSelector>);
});

Slice

From jQuery

1
$(<selector>).slice(<startIndex>, <endIndex>);

to Vanilla JS

1
2
var nodeList = document.querySelectorAll(<selector>);
[].slice.call(nodeList, <startIndex>, <endIndex>);

MANIPULATION

Append

From jQuery

1
2
$(<htmlElement>).append($(<appendHtmlElement>));
// $(<htmlElement>).append(<appendHtmlElement>);

to Vanilla JS

1
2
<htmlElement>.appendChild(<appendHtmlElement>);
// <htmlElement>.insertAdjacentHTML('beforeEnd', <htmlString>);

Clone

From jQuery

1
$(<htmlElement>).clone();

to Vanilla JS

1
<htmlElement>.cloneNode(true);

Compare

From jQuery

1
2
3
4
var $a = $(<selectorToFirstHtmlElement>).find(<selectorToSecondHtmlElement>);
$b = $(<selectorToSecondHtmlElement>);

$a.is($b);

to Vanilla JS

1
2
3
4
5
var temp = document.getElementsByTagName(<selectorToFirstHtmlElement>)[0],
a = temp.getElementsByTagName(<selectorToSecondHtmlElement>)[0],
b = document.querySelector(<selectorToSecondHtmlElement>);

(a === b);

Contains

From jQuery

1
$.contains($(<htmlElement>), $(<childHtmlElement>));

to Vanilla JS

1
(<htmlElement> !== <childHtmlElement>) && <htmlElement>.contains(<childHtmlElement>);

Create

From jQuery

1
$('<' + <tagString> + '>');

to Vanilla JS

1
document.createElement(<tagString>);

Empty

From jQuery

1
$(<htmlElement>).empty();

to Vanilla JS

1
<htmlElement>.innerHTML = '';

Get HTML

From jQuery

1
$(<htmlElement>).html();

to Vanilla JS

1
<htmlElement>.innerHTML;

Get Node HTML

From jQuery

1
$('<div>').append($(<htmlElement>).clone()).html();

to Vanilla JS

1
<htmlElement>.outerHTML;

Get Text

From jQuery

1
$(<htmlElement>).text();

to Vanilla JS

1
<htmlElement>.textContent;

Index From Parent

From jQuery

1
$(<htmlElement>).index();

to Vanilla JS

1
[].slice.call(<htmlElement>.parentNode.children).indexOf(<htmlElement>);

Insert After

From jQuery

1
2
$(<htmlElement>).after($(<afterHtmlElement>));
// $(<htmlElement>).after(<htmlString>);

to Vanilla JS

1
2
<htmlElement>.parentNode.insertBefore(<afterHtmlElement>, <htmlElement>.nextSibling);
// <htmlElement>.insertAdjacentHTML('afterend', <htmlString>);

Insert Before

From jQuery

1
2
$(<htmlElement>).before($(<beforeHtmlElement>));
// $(<htmlElement>).before(<htmlString>);

to Vanilla JS

1
2
<htmlElement>.parentNode.insertBefore(<beforeHtmlElement>, <htmlElement>);
// <htmlElement>.insertAdjacentHTML('beforebegin', <htmlString>);

Prepend

From jQuery

1
2
$(<htmlElement>).prepend($(<prependHtmlElement>));
// $(<htmlElement>).prepend(<htmlString>);

to Vanilla JS

1
2
<htmlElement>.insertBefore(<prependHtmlElement>, <htmlElement>.firstChild);
// <htmlElement>.insertAdjacentHTML('afterBegin', <htmlString>);

Remove

From jQuery

1
$(<htmlElement>).remove();

to Vanilla JS

1
<htmlElement>.parentNode.removeChild(<htmlElement>);

Remove Children

From jQuery

1
$(<htmlElement>).empty();

to Vanilla JS

1
2
3
4
while (<htmlElement>.firstChild) {
<htmlElement>.removeChild(<htmlElement>.firstChild);
}
// <htmlElement>.innerHTML = '';

Replace

From jQuery

1
$(<htmlElement>).replaceWith($(<newHtmlElement>));

to Vanilla JS

1
<htmlElement>.parentNode.replaceChild(<newHtmlElement>, <htmlElement>);

Set HTML

From jQuery

1
$(<htmlElement>).html(<htmlString>);

to Vanilla JS

1
<htmlElement>.innerHTML = <htmlString>;

Set Node HTML

From jQuery

1
$(<htmlElement>).replaceWith(<htmlString>);

to Vanilla JS

1
<htmlElement>.outerHTML = <htmlString>;

Set Text

From jQuery

1
$(<htmlElement>).text(<string>);

to Vanilla JS

1
<htmlElement>.textContent = <string>;

Unwrap

From jQuery

1
$(<htmlElement>).unwrap();

to Vanilla JS

1
2
3
4
while (<htmlElement>.firstChild) {
<unwrapHtmlElement>.insertBefore(<htmlElement>.firstChild, <htmlElement>);
}
<unwrapHtmlElement>.removeChild(<htmlElement>);

Wrap

From jQuery

1
$(<htmlElement>).wrap($(<wrapHtmlElement>));

to Vanilla JS

1
2
<htmlElement>.parentNode.insertBefore(<wrapHtmlElement>, <htmlElement>);
<wrapHtmlElement>.appendChild(<htmlElement>);

TRAVERSING

All Next

From jQuery

1
$(<htmlElement>).nextAll();

to Vanilla JS

1
2
3
4
var nextAll = false;
nextAll = [].filter.call(<htmlElement>.parentNode.children, function (htmlElement) {
return (htmlElement.previousElementSibling === <htmlElement>) ? nextAll = true : nextAll;
});

All Parents

From jQuery

1
var parents = $(<htmlElement>).parents();

to Vanilla JS

1
2
3
4
5
6
var htmlElement = <htmlElement>,
parents = [];
while (htmlElement = htmlElement.parentNode) {
parents.push(htmlElement);
}
parents;

All Previous

From jQuery

1
$(<htmlElement>).prevAll();

to Vanilla JS

1
2
3
4
var prevAll = true;
prevAll = [].filter.call(<htmlElement>.parentNode.children, function (htmlElement) {
return (htmlElement === <htmlElement>) ? prevAll = false : prevAll;
});

Children

From jQuery

1
$(<htmlElement>).children();

to Vanilla JS

1
<htmlElement>.children;

Closest Parent

From jQuery

1
$(<htmlElement>).closest(<parentSelector>);

to Vanilla JS

1
2
3
4
5
6
7
8
9
<htmlElement>.closest(<parentSelector>);

/* // IE fallback
var htmlElement = <htmlElement>,
parents = [];
while (htmlElement = htmlElement.parentNode) {
(htmlElement.matches && htmlElement.matches(<parentSelector>)) ? parents.push(htmlElement) : '';
}
parents[0]; */

Find Children

From jQuery

1
$(<htmlElement>).find(<childrenSelector>);

to Vanilla JS

1
<htmlElement>.querySelectorAll(<childrenSelector>);

First Child

From jQuery

1
$(<htmlElement>).children().first();

to Vanilla JS

1
<htmlElement>.firstChild();

Last Child

From jQuery

1
$(<htmlElement>).children().last();

to Vanilla JS

1
<htmlElement>.lastChild();

Matches Selector

From jQuery

1
$(<htmlElement>).is(<selector>);

to Vanilla JS

1
<htmlElement>.matches(<selector>);

Next

From jQuery

1
$(<htmlElement>).next();

to Vanilla JS

1
2
<htmlElement>.nextElementSibling; // HTMLElement
// <htmlElement>.nextSibling; // Node

Next Until

From jQuery

1
$(<htmlElement>).nextUntil(<nextSelector>);

to Vanilla JS

1
2
3
4
5
6
7
var htmlElement = <htmlElement>,
nextUntil = [],
until = true;
while (htmlElement = htmlElement.nextElementSibling) {
(until && htmlElement && !htmlElement.matches(<nextSelector>)) ? nextUntil.push(htmlElement) : until = false;
}
nextUntil;

Parent

From jQuery

1
$(<htmlElement>).parent();

to Vanilla JS

1
<htmlElement>.parentNode;

Parents

From jQuery

1
var parents = $(<htmlElement>).parents(<parentSelector>);

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var htmlElement = <htmlElement>,
parents = [];
while (htmlElement = htmlElement.parentNode.closest(<parentSelector>)) {
parents.push(htmlElement);
}
parents;

/* // IE fallback
var htmlElement = <htmlElement>,
parents = [];
while (htmlElement = htmlElement.parentNode) {
(htmlElement.matches && htmlElement.matches(<parentSelector>)) ? parents.push(htmlElement) : '';
}
parents; */

Parents Until

From jQuery

1
var parents = $(<htmlElement>).parentsUntil(<parentSelector>);

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var htmlElement = <htmlElement>,
parentsUntil = [],
until = true;
while (htmlElement = htmlElement.parentNode.closest(<parentSelector>)) {
(until) ? parents.push(htmlElement) : until = false;
}
parentsUntil;

/* // IE fallback
var htmlElement = <htmlElement>,
parentsUntil = [],
until = true;
while (htmlElement = htmlElement.parentNode) {
(until && htmlElement.matches && !htmlElement.matches(<parentSelector>)) ? parents.push(htmlElement) : until = false;
}
parentsUntil; */

Previous

From jQuery

1
$(<htmlElement>).prev();

to Vanilla JS

1
2
<htmlElement>.previousElementSibling; // HTMLElement
// <htmlElement>.previousSibling // Node;

Previous Until

From jQuery

1
$(<htmlElement>).prevUntil(<previousSelector>);

to Vanilla JS

1
2
3
4
5
6
7
var htmlElement = <htmlElement>,
previousUntil = [],
until = true;
while (htmlElement = htmlElement.previousElementSibling) {
(until && htmlElement && !htmlElement.matches(<previousSelector>)) ? previousUntil.push(htmlElement) : until = false;
}
previousUntil;

Siblings

From jQuery

1
$(<htmlElement>).siblings();

to Vanilla JS

1
2
3
[].filter.call(<htmlElement>.parentNode.children, function (htmlElement) {
return htmlElement !== <htmlElement>;
});

STYLES

Get Style

From jQuery

1
$(<htmlElement>).css(<property>);

to Vanilla JS

1
getComputedStyle(<htmlElement>)[<property>];

Get Scroll Left

From jQuery

1
$(<htmlElement>).scrollLeft();

to Vanilla JS

1
<htmlElement>.scrollLeft;

Get Scroll Top

From jQuery

1
$(<htmlElement>).scrollTop();

to Vanilla JS

1
<htmlElement>.scrollTop;

Inner Height

From jQuery

1
$(<htmlElement>).innerHeight();

to Vanilla JS

1
<htmlElement>.clientHeight

Inner Width

From jQuery

1
$(<htmlElement>).innerWidth();

to Vanilla JS

1
<htmlElement>.clientWidth

Offset from Document

From jQuery

1
$(<htmlElement>).offset();

to Vanilla JS

1
2
3
4
5
var rect = <htmlElement>.getBoundingClientRect()
{
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}

Offset from Parent

From jQuery

1
$(<htmlElement>).position();

to Vanilla JS

1
2
3
4
{
left: <htmlElement>.offsetLeft,
top: <htmlElement>.offsetTop
}

Offset from Viewport

From jQuery

1
$(<htmlElement>).offset();

to Vanilla JS

1
2
3
4
5
var rect = <htmlElement>.getBoundingClientRect()
{
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}

Outer Height

From jQuery

1
$(<htmlElement>).outerHeight();

to Vanilla JS

1
<htmlElement>.offsetHeight

Outer Width

From jQuery

1
$(<htmlElement>).outerWidth();

to Vanilla JS

1
<htmlElement>.offsetWidth

Parent Not Static

From jQuery

1
$(<htmlElement>).offsetParent();

to Vanilla JS

1
(<htmlElement>.offsetParent || <htmlElement>)

Set Style

From jQuery

1
$(<htmlElement>).css(<property>, <value>);

to Vanilla JS

1
<htmlElement>.style.<property> = <value>;

Set Scroll Left

From jQuery

1
$(<htmlElement>).scrollLeft(<distance>);

to Vanilla JS

1
<htmlElement>.scrollLeft = <distance>;

Set Scroll Top

From jQuery

1
$(<htmlElement>).scrollTop(<distance>);

to Vanilla JS

1
<htmlElement>.scrollTop = <distance>;

UTILS

Array Each

From jQuery

1
2
3
$.each(<array>, function (i, item) {
(item === <array>[i]); // true
});

to Vanilla JS

1
2
3
<array>.forEach(function (item, i) {
(item === <array>[i]); // true
});

Change Futur Context

From jQuery

1
$.proxy(<fn>, <context>);

to Vanilla JS

1
<fn>.bind(<context>);

Extend

From jQuery

1
<object> = $.extend(<extendingObject>, <object>);

to Vanilla JS

1
2
3
4
5
6
7
<object> = Object.assign(<object>, <extendingObject>);

/* // IE fallback (not deep)
Object.keys(<object>).forEach(function (key) {
<object>[key] = (<extendingObject>[key]) ? <extendingObject>[key] : <object>[key];
});
<object>; */

Index Of

From jQuery

1
$.inArray(<item>, <array>);

to Vanilla JS

1
<array>.indexOf(<item>);

Is Array

From jQuery

1
$.isArray(<array>);

to Vanilla JS

1
Array.isArray(<array>);

Map

From jQuery

1
2
3
$.map(<array>, function (item, i) {
return <operations>;
});

to Vanilla JS

1
2
3
<array>.map(function (item, i) {
return <operations>;
});

Now

From jQuery

1
$.now();

to Vanilla JS

1
Date.now();

Parse HTML

From jQuery

1
$.parseHTML(<htmlString>);

to Vanilla JS

1
2
3
4
5
6
7
function parseHTML(htmlString) {
var body = document.implementation.createHTMLDocument().body;
body.innerHTML = htmlString;
return body.childNodes;
}

parseHTML(<htmlString>);

Parse JSON

From jQuery

1
$.parseJSON(<jsonString>);

to Vanilla JS

1
JSON.parse(<jsonString>);

Parse XML

From jQuery

1
$.parseXML(<xmlString>);

to Vanilla JS

1
2
3
4
5
function parseXML(xmlString) {
return (new DOMParser()).parseFromString(xmlString, 'text/xml');
}

parseXML(<xmlString>);

Serialize Array

From jQuery

1
$.serializeArray(<form>);

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function serializeArray(form) {
var field, length, output = [];

if (typeof form === 'object' && form.nodeName === 'FORM') {
var length = form.elements.length;
for (i = 0; i < length; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type !== 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
if (field.type === 'select-multiple') {
length = form.elements[i].options.length;
for (j = 0; j < length; j++) {
if(field.options[j].selected)
output[output.length] = { name: field.name, value: field.options[j].value };
}
} else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
output[output.length] = { name: field.name, value: field.value };
}
}
}
}

return output;
}
serializeArray(<form>);

Serialize String

From jQuery

1
$.serialize(<form>);

to Vanilla JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function serialize(form) {
var field, length, output = [];

if (typeof form === 'object' && form.nodeName === 'FORM') {
var length = form.elements.length;
for (var i = 0; i < length; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type !== 'file' && field.type !== 'reset' && field.type !== 'submit' && field.type !== 'button') {
if (field.type === 'select-multiple') {
length = form.elements[i].options.length;
for (var j=0; j < length; j++) {
if (field.options[j].selected) {
output[output.length] = encodeURIComponent(field.name) + '=' + encodeURIComponent(field.options[j].value);
}
}
} else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
output[output.length] = encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value);
}
}
}
}

return output.join('&').replace(/%20/g, '+');
}
serialize(<form>);

Trim

From jQuery

1
$.trim(<string>);

to Vanilla JS

1
<string>.trim();