vanilla-js-dom
v6.0.118
Published
Vanilla JS is a fast, lightweight, cross-platform framework for building incredible, powerful JavaScript applications.
Downloads
13
Maintainers
Readme
Vanilla JS
Vous êtes français ? Le README derrière ce lien vous sera peut-être plus agréable.
Overview
Vanilla JS is a fast, lightweight, cross-platform tool for building incredible, powerful JavaScript applications.
Use in Development
Just put the following code:
<!-- <script src="path/to/vanilla.js"></script> -->
Use in Production
The much faster method:
Summary
- Overview
- Summary
- Speed Comparison
- From jQuery to Vanilla JS
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 | | jQuery | 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:
<div class="example">
<span>(Text into) Html Element</span>
<!-- Comment Element -->
Text Element
<span>(Text into) Html Element</span>
</div>
querySelector(".example")
return aHTMLElement
.querySelector(".example").children
return aHTMLCollection
, each collection's item is aHTMLElement
, two[span, span]
here.querySelector(".example").childNodes
return aNodeList
, each collection's item is aNode
, seven[text, span, text, comment, text, span, text]
here.querySelector(".example").childNodes[0]
return aText
(Node
) oftypeNode
3, as a text. (...nodeList[3]
istypeNode
8 as aComment
(Node
too)).
.Node #Selector
#id
From jQuery
var htmlElement = $("#id")[0];
to Vanilla JS
var htmlElement = document.getElementById("id");
.classname #id tagname
From jQuery
var htmlElement = $("#id .classname tagname")[0];
to Vanilla JS
document.querySelector("#id .classname tagname");
[.classname #id tagname]
From jQuery
$("#id .classname tagname").each(function (i, htmlElement) {
htmlElement;
});
to Vanilla JS
var nodeList = document.querySelectorAll("#id .classname tagname"); // Not Live (Snapshot)
[].forEach.call(nodeList, function (node) {
node;
});
[.classname]
From jQuery
$(".classname").each(function (i, htmlElement) {
htmlElement;
});
to Vanilla JS
var htmlCollection = document.getElementsByClassName("classname"); // Live
// var nodeList = document.querySelectorAll(".classname"); // Not Live (Snapshot)
[].forEach.call(htmlCollection, function (htmlElement) {
htmlElement;
});
[name]
From jQuery
$('[name="name"]').each(function (i, htmlElement) {
htmlElement;
});
to Vanilla JS
var nodeList = document.getElementsByName("name"); // Live
// var nodeList = document.querySelectorAll("[name=name]"); // Not Live (Snapshot)
[].forEach.call(nodeList, function (node) {
node;
});
[tagname]
From jQuery
$("tagname").each(function (i, htmlElement) {
htmlElement;
});
to Vanilla JS
var htmlCollection = document.getElementsByTagName("tagname"); // Live
// var nodeList = document.querySelectorAll("tagname"); // Not Live (Snapshot)
[].forEach.call(htmlCollection, function (htmlElement) {
htmlElement;
});
Reverted Loop
From jQuery
$($(".className").get().reverse()).each(function (i, htmlElement) {
htmlElement;
});
to Vanilla JS
var htmlCollection = document.getElementsByClassName("className"), // Live
i = htmlCollection.length;
while (htmlElement = htmlCollection[--i]) {
htmlElement;
}
AJAX
GET
From jQuery
$.ajax({
type: "GET",
url: <url>,
data: <data>
});
to Vanilla JS
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
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
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
$.ajax({
type: "POST",
url: <url>,
data: <data>
});
to Vanilla JS
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
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
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
$(<htmlElement>).addClass(<className>);
to Vanilla JS
<htmlElement>.classList.add(<className>);
Get Attribute
From jQuery
$(<htmlElement>).attr(<attributeName>);
to Vanilla JS
<htmlElement>.getAttribute(<attributeName>);
Get Data
From jQuery
$(<htmlElement>).data(<dataName>);
to Vanilla JS
<htmlElement>.getAttribute(<"data-" + dataName>);
Get Value
From jQuery
$(<htmlElement>).value();
to Vanilla JS
<htmlElement>.value;
Has Class
From jQuery
$(<htmlElement>).hasClass(<className>);
to Vanilla JS
<htmlElement>.classList.contains(<className>);
Remove Attribute
From jQuery
$(<htmlElement>).removeAttr(<attributeName>);
to Vanilla JS
<htmlElement>.removeAttribute(<attributeName>);
Remove Class
From jQuery
$(<htmlElement>).removeClass(<className>);
to Vanilla JS
<htmlElement>.classList.remove(<className>);
Remove Data
From jQuery
$(<htmlElement>).removeData(<dataName>);
to Vanilla JS
<htmlElement>.removeAttribute(<"data-" + dataName>);
Set Attribute
From jQuery
$(<htmlElement>).attr(<attributeName>, <value>);
to Vanilla JS
<htmlElement>.setAttribute(<attributeName>, <value>);
Set Data
From jQuery
$(<htmlElement>).data(<dataName>, <value>);
to Vanilla JS
<htmlElement>.setAttribute(<"data-" + dataName>, <value>);
Set Value
From jQuery
$(<htmlElement>).value(<value>);
to Vanilla JS
<htmlElement>.value = <value>;
Toggle Class
From jQuery
$(<htmlElement>).toggleClass(<className>);
to Vanilla JS
<htmlElement>.classList.toggle(<className>);
EFFECTS
Animation
From jQuery
function fadeIn($htmlElement, speed, next) {
$htmlElement.css("opacity", "0").animate({ opacity: 1 }, speed, next);
}
fadeIn($(<htmlElement>), 2000, function () {
$(this).css("opacity", "");
});
to Vanilla JS
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
$(<htmlElement>).hide();
to Vanilla JS
<htmlElement>.style.display = "none";
Show
From jQuery
$(<htmlElement>).show();
to Vanilla JS
<htmlElement>.style.display = "";
EVENTS
Hover
From jQuery
$(<htmlElement>).hover(<eventHandlerMouseIn>, <eventHandlerMouseOut>);
to Vanilla JS
<htmlElement>.addEventListener("mouseenter", <eventHandlerMouseIn>);
<htmlElement>.addEventListener("mouseleave", <eventHandlerMouseOut>);
Load
From jQuery
$(<htmlElement>).load(function () {
// I am full loaded.
});
to Vanilla JS
<htmlElement>.addEventListener("load", function () {
// I am full loaded.
});
Off
From jQuery
$(<htmlElement>).off(<eventName>, <eventHandler>);
to Vanilla JS
<htmlElement>.removeEventListener(<eventName>, <eventHandler>);
On
From jQuery
$(<htmlElement>).on(<eventName>, <eventHandler>);
to Vanilla JS
<htmlElement>.addEventListener(<eventName>, <eventHandler>);
One
From jQuery
$(<htmlElement>).one(<eventName>, <eventHandler>);
to Vanilla JS
<htmlElement>.addEventListener(<eventName>, function callee(event) {
event.target.removeEventListener(e.type, callee);
});
Ready
From jQuery
$(document).ready(function () {
// I am ready to be manipulate.
});
to Vanilla JS
document.addEventListener("DOMContentLoaded", function () {
// I am ready to be manipulate.
});
Trigger
From jQuery
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
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
$(<selector>).filter(function (i, htmlElement) {
return <filterCondition>;
}).each(function (i, htmlElement) {
htmlElement;
});
to Vanilla JS
var nodeList = document.querySelectorAll(<selector>);
nodeList = [].filter.call(nodeList, function (node) {
return <filterCondition>;
});
[].forEach.call(nodeList, function (node) {
node;
});
First
From jQuery
$(<selector>).first();
to Vanilla JS
<htmlCollection>.item(0);
// <htmlCollection>[0];
Has
From jQuery
$(<selector>).has(<matchesChildSelector>);
to Vanilla JS
var nodeList = document.querySelectorAll(<selector>);
[].filter.call(nodeList, function (node) {
return node.querySelector(<matchesChildSelector>);
});
Is
From jQuery
$(<selector>).is(<matchesSelector>);
to Vanilla JS
var nodeList = document.querySelectorAll(<selector>);
[].some.call(nodeList, function (node) {
return node.matches(<matchesSelector>);
});
Item
From jQuery
$(<selector>).eq(<index>);
to Vanilla JS
<htmlCollection>.item(<index>);
// <htmlCollection>[<index>];
Last
From jQuery
$(<selector>).last();
to Vanilla JS
<htmlCollection>.item(<htmlCollection>.length - 1);
// <htmlCollection>[<htmlCollection>.length - 1];
Not
From jQuery
$(<selector>).not(<matchesSelector>);
to Vanilla JS
var nodeList = document.querySelectorAll(<selector>);
[].filter.call(nodeList, function (node) {
return !node.matches(<matchesSelector>);
});
Slice
From jQuery
$(<selector>).slice(<startIndex>, <endIndex>);
to Vanilla JS
var nodeList = document.querySelectorAll(<selector>);
[].slice.call(nodeList, <startIndex>, <endIndex>);
MANIPULATION
Append
From jQuery
$(<htmlElement>).append($(<appendHtmlElement>));
// $(<htmlElement>).append(<appendHtmlElement>);
to Vanilla JS
<htmlElement>.appendChild(<appendHtmlElement>);
// <htmlElement>.insertAdjacentHTML("beforeEnd", "<htmlString>");
Clone
From jQuery
$(<htmlElement>).clone();
to Vanilla JS
<htmlElement>.cloneNode(true);
Compare
From jQuery
var $a = $(<selectorToFirstHtmlElement>).find(<selectorToSecondHtmlElement>);
$b = $(<selectorToSecondHtmlElement>);
$a.is($b);
to Vanilla JS
var temp = document.getElementsByTagName(<selectorToFirstHtmlElement>)[0],
a = temp.getElementsByTagName(<selectorToSecondHtmlElement>)[0],
b = document.querySelector(<selectorToSecondHtmlElement>);
(a === b);
Contains
From jQuery
$.contains($(<htmlElement>), $(<childHtmlElement>));
to Vanilla JS
(<htmlElement> !== <childHtmlElement>) && <htmlElement>.contains(<childHtmlElement>);
Create
From jQuery
$(<<tagString>>);
to Vanilla JS
document.createElement(<tagString>);
Empty
From jQuery
$(<htmlElement>).empty();
to Vanilla JS
<htmlElement>.innerHTML = "";
Get HTML
From jQuery
$(<htmlElement>).html();
to Vanilla JS
<htmlElement>.innerHTML;
Get Node HTML
From jQuery
$("<div>").append($(<htmlElement>).clone()).html();
to Vanilla JS
<htmlElement>.outerHTML;
Get Text
From jQuery
$(<htmlElement>).text();
to Vanilla JS
<htmlElement>.textContent;
Index From Parent
From jQuery
$(<htmlElement>).index();
to Vanilla JS
[].slice.call(<htmlElement>.parentNode.children).indexOf(<htmlElement>);
Insert After
From jQuery
$(<htmlElement>).after($(<afterHtmlElement>));
// $(<htmlElement>).after(<htmlString>);
to Vanilla JS
<htmlElement>.parentNode.insertBefore(<afterHtmlElement>, <htmlElement>.nextSibling);
// <htmlElement>.insertAdjacentHTML("afterend", <htmlString>);
Insert Before
From jQuery
$(<htmlElement>).before($(<beforeHtmlElement>));
// $(<htmlElement>).before(<htmlString>);
to Vanilla JS
<htmlElement>.parentNode.insertBefore(<beforeHtmlElement>, <htmlElement>);
// <htmlElement>.insertAdjacentHTML("beforebegin", <htmlString>);
Prepend
From jQuery
$(<htmlElement>).prepend($(<prependHtmlElement>));
// $(<htmlElement>).prepend(<htmlString>);
to Vanilla JS
<htmlElement>.insertBefore(<prependHtmlElement>, <htmlElement>.firstChild);
// <htmlElement>.insertAdjacentHTML("afterBegin", "<htmlString>");
Remove
From jQuery
$(<htmlElement>).remove();
to Vanilla JS
<htmlElement>.parentNode.removeChild(<htmlElement>);
Remove Children
From jQuery
$(<htmlElement>).empty();
to Vanilla JS
while (<htmlElement>.firstChild) {
<htmlElement>.removeChild(<htmlElement>.firstChild);
}
// <htmlElement>.innerHTML = '';
Replace
From jQuery
$(<htmlElement>).replaceWith($(<newHtmlElement>));
to Vanilla JS
<htmlElement>.parentNode.replaceChild(<newHtmlElement>, <htmlElement>);
Set HTML
From jQuery
$(<htmlElement>).html(<htmlString>);
to Vanilla JS
<htmlElement>.innerHTML = <htmlString>;
Set Node HTML
From jQuery
$(<htmlElement>).replaceWith(<htmlString>);
to Vanilla JS
<htmlElement>.outerHTML = <htmlString>;
Set Text
From jQuery
$(<htmlElement>).text(<string>);
to Vanilla JS
<htmlElement>.textContent = <string>;
Unwrap
From jQuery
$(<htmlElement>).unwrap();
to Vanilla JS
while (<htmlElement>.firstChild) {
<unwrapHtmlElement>.insertBefore(<htmlElement>.firstChild, <htmlElement>);
}
<unwrapHtmlElement>.removeChild(<htmlElement>);
Wrap
From jQuery
$(<htmlElement>).wrap($(<wrapHtmlElement>));
to Vanilla JS
<htmlElement>.parentNode.insertBefore(<wrapHtmlElement>, <htmlElement>);
<wrapHtmlElement>.appendChild(<htmlElement>);
TRAVERSING
All Next
From jQuery
$(<htmlElement>).nextAll();
to Vanilla JS
var nextAll = false;
nextAll = [].filter.call(<htmlElement>.parentNode.children, function (htmlElement) {
return (htmlElement.previousElementSibling === <htmlElement>) ? nextAll = true : nextAll;
});
All Parents
From jQuery
var parents = $(<htmlElement>).parents();
to Vanilla JS
var htmlElement = <htmlElement>,
parents = [];
while (htmlElement = htmlElement.parentNode) {
parents.push(htmlElement);
}
parents;
All Previous
From jQuery
$(<htmlElement>).prevAll();
to Vanilla JS
var prevAll = true;
prevAll = [].filter.call(<htmlElement>.parentNode.children, function (htmlElement) {
return (htmlElement === <htmlElement>) ? prevAll = false : prevAll;
});
Children
From jQuery
$(<htmlElement>).children();
to Vanilla JS
<htmlElement>.children;
Closest Parent
From jQuery
$(<htmlElement>).closest(<parentSelector>);
to Vanilla JS
var htmlElement = <htmlElement>,
parents = [];
while (htmlElement = htmlElement.parentNode) {
(htmlElement.matches && htmlElement.matches(<parentSelector>)) ? parents.push(htmlElement) : "";
}
parents[0];
// <htmlElement>.closest(<parentSelector>); // More fast but not supported by IE/EDGE
Find Children
From jQuery
$(<htmlElement>).find(<childrenSelector>);
to Vanilla JS
<htmlElement>.querySelectorAll(<childrenSelector>);
First Child
From jQuery
$(<htmlElement>).children().first();
to Vanilla JS
<htmlElement>.firstChild();
Last Child
From jQuery
$(<htmlElement>).children().last();
to Vanilla JS
<htmlElement>.lastChild();
Matches Selector
From jQuery
$(<htmlElement>).is(<selector>);
to Vanilla JS
<htmlElement>.matches(<selector>);
Next
From jQuery
$(<htmlElement>).next();
to Vanilla JS
<htmlElement>.nextElementSibling; // HTMLElement
// <htmlElement>.nextSibling; // Node
Next Until
From jQuery
$(<htmlElement>).nextUntil(<nextSelector>);
to Vanilla JS
var htmlElement = <htmlElement>,
nextUntil = [],
until = true;
while (htmlElement = htmlElement.nextElementSibling) {
(until && htmlElement && !htmlElement.matches(<nextSelector>)) ? nextUntil.push(htmlElement) : until = false;
}
nextUntil;
Parent
From jQuery
$(<htmlElement>).parent();
to Vanilla JS
<htmlElement>.parentNode;
Parents
From jQuery
var parents = $(<htmlElement>).parents(<parentSelector>);
to Vanilla JS
var htmlElement = <htmlElement>,
parents = [];
while (htmlElement = htmlElement.parentNode) {
(htmlElement.matches && htmlElement.matches(<parentSelector>)) ? parents.push(htmlElement) : "";
/* // More fast alternative but not supported by IE/Edge
while (htmlElement = htmlElement.parentNode.closest(<parentSelector>)) {
parents.push(htmlElement); */
}
parents;
Parents Until
From jQuery
var parents = $(<htmlElement>).parentsUntil(<parentSelector>);
to Vanilla JS
var htmlElement = <htmlElement>,
parentsUntil = [],
until = true;
while (htmlElement = htmlElement.parentNode) {
(until && htmlElement.matches && !htmlElement.matches(<parentSelector>)) ? parents.push(htmlElement) : until = false;
/* // More fast alternative but not supported by IE/Edge
while (htmlElement = htmlElement.parentNode.closest(<parentSelector>)) {
(until) ? parents.push(htmlElement) : until = false; */
}
parentsUntil;
Previous
From jQuery
$(<htmlElement>).prev();
to Vanilla JS
<htmlElement>.previousElementSibling; // HTMLElement
// <htmlElement>.previousSibling // Node;
Previous Until
From jQuery
$(<htmlElement>).prevUntil(<previousSelector>);
to Vanilla JS
var htmlElement = <htmlElement>,
previousUntil = [],
until = true;
while (htmlElement = htmlElement.previousElementSibling) {
(until && htmlElement && !htmlElement.matches(<previousSelector>)) ? previousUntil.push(htmlElement) : until = false;
}
previousUntil;
Siblings
From jQuery
$(<htmlElement>).siblings();
to Vanilla JS
[].filter.call(<htmlElement>.parentNode.children, function (htmlElement) {
return htmlElement !== <htmlElement>;
});
STYLES
Get Style
From jQuery
$(<htmlElement>).css(<property>);
to Vanilla JS
getComputedStyle(<htmlElement>)[<property>];
Get Scroll Left
From jQuery
$(<htmlElement>).scrollLeft();
to Vanilla JS
<htmlElement>.scrollLeft;
Get Scroll Top
From jQuery
$(<htmlElement>).scrollTop();
to Vanilla JS
<htmlElement>.scrollTop;
Inner Height
From jQuery
$(<htmlElement>).innerHeight();
to Vanilla JS
<htmlElement>.clientHeight
Inner Width
From jQuery
$(<htmlElement>).innerWidth();
to Vanilla JS
<htmlElement>.clientWidth
Offset from Document
From jQuery
$(<htmlElement>).offset();
to Vanilla JS
var rect = <htmlElement>.getBoundingClientRect()
{
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}
Offset from Parent
From jQuery
$(<htmlElement>).position();
to Vanilla JS
{
left: <htmlElement>.offsetLeft,
top: <htmlElement>.offsetTop
}
Offset from Viewport
From jQuery
$(<htmlElement>).offset();
to Vanilla JS
var rect = <htmlElement>.getBoundingClientRect()
{
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}
Outer Height
From jQuery
$(<htmlElement>).outerHeight();
to Vanilla JS
<htmlElement>.offsetHeight
Outer Width
From jQuery
$(<htmlElement>).outerWidth();
to Vanilla JS
<htmlElement>.offsetWidth
Parent Not Static
From jQuery
$(<htmlElement>).offsetParent();
to Vanilla JS
(<htmlElement>.offsetParent || <htmlElement>)
Set Style
From jQuery
$(<htmlElement>).css(<property>, <value>);
to Vanilla JS
<htmlElement>.style.<property> = <value>;
Set Scroll Left
From jQuery
$(<htmlElement>).scrollLeft(<distance>);
to Vanilla JS
<htmlElement>.scrollLeft = <distance>;
Set Scroll Top
From jQuery
$(<htmlElement>).scrollTop(<distance>);
to Vanilla JS
<htmlElement>.scrollTop = <distance>;
UTILS
Array Each
From jQuery
$.each(<array>, function (i, item) {
(item === <array>[i]); // true
});
to Vanilla JS
<array>.forEach(function (item, i) {
(item === <array>[i]); // true
});
Change Futur Context
From jQuery
$.proxy(<fn>, <context>);
to Vanilla JS
<fn>.bind(<context>);
Extend
From jQuery
<object> = $.extend(<extendingObject>, <object>);
to Vanilla JS
// <object> = Object.assign(<object>, <extendingObject>); // Deep extend but not supported by IE
Object.keys(<object>).forEach(function (key) {
<object>[key] = (<extendingObject>[key]) ? <extendingObject>[key] : <object>[key];
});
<object>;
Index Of
From jQuery
$.inArray(<item>, <array>);
to Vanilla JS
<array>.indexOf(<item>);
Is Array
From jQuery
$.isArray(<array>);
to Vanilla JS
Array.isArray(<array>);
Map
From jQuery
$.map(<array>, function (item, i) {
return <operations>;
});
to Vanilla JS
<array>.map(function (item, i) {
return <operations>;
});
Now
From jQuery
$.now();
to Vanilla JS
Date.now();
Parse HTML
From jQuery
$.parseHTML(<htmlString>);
to Vanilla JS
function parseHTML(htmlString) {
var body = document.implementation.createHTMLDocument().body;
body.innerHTML = htmlString;
return body.childNodes;
}
parseHTML(<htmlString>);
Parse JSON
From jQuery
$.parseJSON(<jsonString>);
to Vanilla JS
JSON.parse(<jsonString>);
Parse XML
From jQuery
$.parseXML(<xmlString>);
to Vanilla JS
function parseXML(xmlString) {
return (new DOMParser()).parseFromString(xmlString, "text/xml");
}
parseXML(<xmlString>);
Serialize Array
From jQuery
$.serializeArray(<form>);
to Vanilla JS
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
$.serialize(<form>);
to Vanilla JS
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
$.trim(<string>);
to Vanilla JS
<string>.trim();