| jQuery | Vanilla |
|---|---|
| ```javascript $(document).ready(function() { })``` | ```javascript document.addEventListener('DOMContentLoaded', function() { })``` |
| ```javascript var divs = $('div')``` | ```javascript var divs = document.querySelectorAll('div')``` |
| `var newDiv = $(' ')` | `var newDiv = document.createElement('div')` |
| `newDiv.addClass('foo')` | `newDiv.classList.add('foo')` |
| `newDiv.toggleClass('foo') | newDiv.classList.toggle('foo') |
| `$('a').click(function() { // code… })` | `[].forEach.call(document.querySelectorAll('a'), function(el) { el.addEventListener('click', function() { // code… }) })` |
| `$('body').append($(' ')) | document.body.appendChild(document.createElement('p')) |
| `$('img').filter(':first').attr('alt', 'My image') | document.querySelector('img').setAttribute('alt', 'My image') |
| `var parent = $('#about').parent()` | `var parent = document.getElementById('about').parentNode` |
| `var clonedElement = $('#about').clone()` | var clonedElement = document.getElementById('about').cloneNode(true) |
| `$('#wrap').empty()` | `var wrap = document.getElementById('wrap') while(wrap.firstChild) wrap.removeChild(wrap.firstChild)` |
| `if($('#wrap').is(':empty'))` | `if(!document.getElementById('wrap').hasChildNodes())` |
| `var nextElement = $('#wrap').next()` | `var nextElement = document.getElementById('wrap').nextSibling` |
-
Star
(1,238)
You must be signed in to star a gist -
Fork
(230)
You must be signed in to fork a gist
-
-
Save joyrexus/7307312 to your computer and use it in GitHub Desktop.
$('selector').load() would be nice 👍
@yairEO ,
I found a good JQuery wrap() method in plain Javascript: [(https://plainjs.com/javascript/manipulation/wrap-an-html-structure-around-an-element-28/)]
@brmendez ,
there is an alternative for JQuery load() method: loadPageSection.js
[(https://gist.github.com/lazamar/f213d94d08a8212bb0a59a4ec2fbc964)]
I am rewriting one of my projects that has jQuery as a dependency to not have any dependencies. I was googling each line I needed to change until I found this. This is very useful, thank you.
I'm currently learning javascript and jQuery. This helps out tremendously! Thank you!
Base on jQuery's doc
By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example,
). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
These methods will execute code, while the vanilla method will not eval scripts.
$(btn[index++]).click();
whats evq for that?
document.querySelector(btn[index++]).click();
how about eq() ? What is eq() is vanilla js?
what about this?
$( document ).ajaxComplete(function() {
// code here to change element, witch is loaded with ajax
});
Thanks for the great resource!
For the following:
// jQuery
$('#wrap').empty()
// Vanilla
var wrap = document.getElementById('wrap')
while(wrap.firstChild) wrap.removeChild(wrap.firstChild)
Why not wrap.innerHTML = '' or similar?
The while loop poses a problem if you are, e.g., ensuring that data refreshes probably -- since it will clear out anything you subsequently put into the element.
while is faster than $().empty or wrap.innerHTML = ""
nobody cares about performance?
document.querySelectorAll('a') change to document.getElementsByTagName('a') why? first is browser API second i native.
you should check out this video btw.
https://youtu.be/VBfvnKDlZMw?t=597
thank you
this is very useful :)
I think jQuery Append method is perfect for all types of DOM manipulations. @brmendez $('selector').load() method is removed few years back, now there is .load() method for doing AJAX request only.
Thanks!
Fetch is also widely supported now. Fully supported with a relatively lightweight pollyfill for IE. So AJAX calls are just as easy with Vanilla JS now as with jQuery. :)
I finally found a way to get the vanilla js equivalent of:
var item = $('form input');
var todo = {item: item.val()};
it is simple! here it is:
var item = document.querySelectorAll('input')[0];
var todo = {item: item.value)};
I was trying to use innerHTML, text etc, but is simply .value :)
love it! Maybe add a $(el).closest() equivalent?
@jfudman
love it! Maybe add a
$(el).closest()equivalent?
It's also .closest() https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
While this may be true, the browser support for many of those methods are somewhat different. Methods like classList.add may not be supported in older browsers.
Just take a moment to see how long and tedious polyfill for classList is.
Fetch is also widely supported now. Fully supported with a relatively lightweight pollyfill for IE. So AJAX calls are just as easy with Vanilla JS now as with jQuery. :)
Yes....
$('selector').load() would be nice 👍
`
// You can do something like:
< div class="include" data-file="./components/footer.html">
document.querySelectorAll('include').forEach((tag) => {
fetch(tag.dataset.file)
.then((r) => r.text())
.then((r) => $(tag).replaceWith($(r)))
})
`
$('#wrap').next()is not the same at all as vanillanextSibling, but tonextElementSibling, because obviouslynextSiblingreturns text nodes which are irrelevant.Regarding the example of
$('img').filter(':first').attr('alt', 'My image')- nobody in their right mind will use filter like that. you would simply do:$('img:first') $('img').eq(0) $('img:eq(0)')would be nice to add vanillia of
wrap()method anddata()method for storing data on a cached object
An implementation of jQuery's wrap() might be as follows:
In HTML:
<input type="text" id="textInput"/>
In jQuery:
$('#textInput').wrap('<div class="wrapped-input"></div>');
In JS:
/**
* Creates a tag element, appends the specified child element to it and
* then appends the created tag to the child's parent element.
* @param {HTMLElement} child The child element to be contained in a new
* wrapper element.
* @param {string} Optional: The name of the tag element to create.
* @returns HTMLElement The newly created tag element wrapped around child.
*/
function wrap(child, tag) {
if (!tag) tag = "div";
const parent = child.parentElement;
const elm = document.createElement("" + tag); // ensures that 'tag' is really a string
elm.appendChild(child);
parent.appendChild(elm);
return elm;
}
Usage:
wrap(document.getElementById('textInput')).setAttribute('class', 'wrapped-input');
This is why jQuery will never die. Why would any programmer want to use vanilla JS? Three times as many characters in vanilla Javascript to perform the same function as jQuery. Ridiculous. The performance difference doesn't justify the overly complicated and difficult-to-read syntax of vanilla JS.
This is why jQuery will never die. Why would any programmer want to use vanilla JS? Three times as many characters in vanilla Javascript to perform the same function as jQuery. Ridiculous. The performance difference doesn't justify the overly complicated and difficult-to-read syntax of vanilla JS.
For the same reason people sometimes prefer to use vanilla css isntead of a framework. even if you are only using 1 method of jquery, the whole library gets loaded along with the page, which makes for a really heavy page
While I'm glad for the examples to learn more vanilla js, I gotta say that every single one is far more verbose then the jQuery equivalent. Some are even excessively so. That alone makes me want to stick with jQuery. I just don't see any good reason to switch to Vanilla JS unless I am using a framework like Vue.js. I just haven't heard any truly compelling arguments.
While I'm glad for the examples to learn more vanilla js, I gotta say that every single one is far more verbose then the jQuery equivalent. Some are even excessively so. That alone makes me want to stick with jQuery. I just don't see any good reason to switch to Vanilla JS unless I am using a framework like Vue.js. I just haven't heard any truly compelling arguments.
Benchmark your pagespeed with and without. Look on a large website for time the browser spends on scripting with jQuery vs without. Its a pretty resource-expensive library to simply query dom elements.
Nice discussion. I would like to see if anyone have a pure javascript solution for following code:
Thanks.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Select Box</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<h2>Select Box</h2>
<form action="">
<SELECT class="combine" id ="command" name = "a">
<option></option>
<option>SELECT</option>
<option>Digital Write</option>
<option>Analog Write</option>
<option>Digital Read</option>
<option>Analog Read</option>
<option>Neopixel</option>
<option>Set AP Channel</option>
<option>Set Sleep Time</option>
<option>Set Mode</option>
</SELECT>
<SELECT class="combine" id ="device" name = "b">
<option></option>
<option>Livingroom</option>
<option>Kitchen</option>
<option>Bedroom1</option>
<option>Bedroom2</option>
<option>Bathroom1</option>
<option>Bathroom2</option>
<option>Laundry</option>
<option>Office</option>
</SELECT>
<SELECT class="combine" id ="command1" name = "c" >
<option>00</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
</SELECT>
<SELECT class="combine" id ="command2" name = "d">
<option>00</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
</SELECT>
<SELECT class="combine" id ="command3" name = "e">
<option>00</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
</SELECT>
<SELECT class="combine" id ="command4" name = "f" >
<option>00</option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
</SELECT>
<br>
<script>
var attachEvent = function(node, event, listener, useCapture) {
// Method for FF, Opera, Chrome, Safari
if ( window.addEventListener ) {
node.addEventListener(event, listener, useCapture || false);
}
// IE has its own method
else {
node.attachEvent('on'+event, listener);
}
};
// Once the window loads and the DOM is ready, attach the event to the main
attachEvent(window, "load", function() {
var select_command = document.getElementById("command");
var selectHandler = function() {
option1 = document.getElementById("device"),
option2 = document.getElementById("command1");
option3 = document.getElementById("command2");
option4 = document.getElementById("command3");
option5 = document.getElementById("command4");
// Show and hide the appropriate select's
if (this.value == "Neopixel") {
option1.style.display = "";
option2.style.display = "";
option3.style.display = "";
option4.style.display = "";
option5.style.display = "";
} else if (this.value == "Set AP Channel" || this.value == "Set Sleep Time" || this.value == "Set Mode" || this.value == "Digital Read" || this.value == "Analog Read") {
option1.style.display = "";
option2.style.display = "";
option3.style.display = "none";
option4.style.display = "none";
option5.style.display = "none";
} else if (this.value == "Digital Write" || this.value == "Analog Write" || this.value == "SELECT") {
option1.style.display = "";
option2.style.display = "";
option3.style.display = "";
option4.style.display = "none";
option5.style.display = "none";
if (this.value == "SELECT") {
option1.style.display = "none";
option2.style.display = "none";
option3.style.display = "none";
option4.style.display = "none";
option5.style.display = "none";
}
}
};
// Use the onchange and onkeypress events to detect when the
// value of select_command has changed
attachEvent(select_command, "change", selectHandler);
attachEvent(select_command, "keypress", selectHandler);
});
$(document).ready(function(){
$("form").submit(function(){
var sentCommand = document.getElementById('result').value;
});
});
$(document).ready(function(){
$('.combine').on('change', function(){
if ($('#command').val() == "Set AP Channel" || "Set Sleep Time" || "Set Mode" || "Digital Read" || "Analog Read")
{
var payload = $('#command').val() + '/' + $('#device').val() + '/' + $('#command1').val();
}
if ($('#command').val() == "Digital Write")
{
var payload = $('#command').val() + '/' + $('#device').val() + '/' + $('#command1').val() + "/" + $('#command2').val();
}
if ($('#command').val() == "Neopixel")
{
var payload = $('#command').val() + '/' + $('#device').val() + '/' + $('#command1').val() + "/" + $('#command2').val() + '/' + $('#command3').val() + '/' + $('#command4').val() ;
}
$('#result').val(payload);
});
})
</script>
<br>
<input type="text" id="result" size = "52" name="send" value="" />
<input type="submit" value="Send Command">
</form>
</body>
</html>
$('#wrap').next()is not the same at all as vanillanextSibling, but tonextElementSibling, because obviouslynextSiblingreturns text nodes which are irrelevant.Regarding the example of
$('img').filter(':first').attr('alt', 'My image')- nobody in their right mind will use filter like that. you would simply do:would be nice to add vanillia of
wrap()method anddata()method for storing data on a cached object