Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Forked from liamcurry/gist:2597326
Last active November 5, 2024 14:17
Show Gist options
  • Save joyrexus/7307312 to your computer and use it in GitHub Desktop.
Save joyrexus/7307312 to your computer and use it in GitHub Desktop.
Vanilla JS equivalents of jQuery methods

Sans jQuery

Events

// jQuery
$(document).ready(function() {
  // code
})

// Vanilla
document.addEventListener('DOMContentLoaded', function() {
  // code
})
// jQuery
$('a').click(function() {
  // code…
})

// Vanilla
[].forEach.call(document.querySelectorAll('a'), function(el) {
  el.addEventListener('click', function() {
    // code…
  })
})

Selectors

// jQuery
var divs = $('div')

// Vanilla
var divs = document.querySelectorAll('div')
// jQuery
var newDiv = $('<div/>')

// Vanilla
var newDiv = document.createElement('div')

Attributes

// jQuery
$('img').filter(':first').attr('alt', 'My image')

// Vanilla
document.querySelector('img').setAttribute('alt', 'My image')

Classes

// jQuery
newDiv.addClass('foo')

// Vanilla
newDiv.classList.add('foo')
// jQuery
newDiv.toggleClass('foo')

// Vanilla
newDiv.classList.toggle('foo')

Manipulation

// jQuery
$('body').append($('<p/>'))

// Vanilla
document.body.appendChild(document.createElement('p'))
// jQuery
var clonedElement = $('#about').clone()

// Vanilla
var clonedElement = document.getElementById('about').cloneNode(true)
// jQuery
$('#wrap').empty()

// Vanilla
var wrap = document.getElementById('wrap')
while(wrap.firstChild) wrap.removeChild(wrap.firstChild)

Transversing

// jQuery
var parent = $('#about').parent()

// Vanilla
var parent = document.getElementById('about').parentNode
// jQuery
if($('#wrap').is(':empty'))

// Vanilla
if(!document.getElementById('wrap').hasChildNodes())
// jQuery
var nextElement = $('#wrap').next()

// Vanilla
var nextElement = document.getElementById('wrap').nextSibling

AJAX

GET

// jQuery
$.get('//example.com', function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.open('GET', url)
httpRequest.send()

POST

// jQuery
$.post('//example.com', { username: username }, function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.open('POST', url)
httpRequest.send('username=' + encodeURIComponent(username))

JSONP

// jQuery
$.getJSON('//openexchangerates.org/latest.json?callback=?', function (data) {
  // code
})

// Vanilla
function success(data) {
  // code
}
var scr = document.createElement('script')
scr.src = '//openexchangerates.org/latest.json?callback=formatCurrency'
document.body.appendChild(scr)

More

Here are a few additional references demonstrating vanilla javascript equivalents of jquery methods:

Also, see the two part series showing equivalents for ...

@johnsfuller
Copy link

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.

@happytm
Copy link

happytm commented May 7, 2022

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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment