This content originally appeared on Envato Tuts+ Tutorials and was authored by Anna Monus
Even though jQuery is still a popular JavaScript library and has a place in web development, native web APIs have evolved a lot in recent years. As modern browsers support a wide range of JavaScript functionalities, we no longer need a third-party library to manipulate the DOM with relative ease. As a result, many frontend developers have decided to move from jQuery to JavaScript to decrease the number of dependencies and thus page load times.
To help you with the move, here’s a jQuery to JavaScript cheat sheet that includes the JavaScript equivalents to the most frequently used jQuery functionality.
jQuery vs. JavaScript
jQuery is a JavaScript library that helps web developers manipulate the document object model (DOM) to dynamically react to user actions and state changes. Its biggest advantage is that it lets you easily select any DOM element on the page and add user actions to it by using the “dot notation”, for instance:
/* Adds the .active class to the toggle button */ $('#toggle').addClass('active');
Native JavaScript is more verbose, you can’t just add actions to any DOM element–first you need to pass it to a variable, then you can perform different actions on it. For instance, this is how the code above looks in JavaScript:
let toggle = document.querySelector('#toggle'); toggle.classList.add('active');
Even though JavaScript is more verbose, you don’t have to use a third-party library, as the DOM API (that you call with your JavaScript code) is built into your web browser. As a result, you’ll have one less dependency and in most cases, your page will also load faster than with jQuery. However you need to judge for yourself if it’s worth moving to native JavaScript as you’ll need to write more code to achieve the same result. So, the trade-off between jQuery and JavaScript is more custom-written code vs. fewer dependencies.
Now, let’s see the 30 most commonly used jQuery to JavaScript equivalents.
1. Select Elements
jQuery:
The jQuery()
function, or $()
in short, is the global function in jQuery that you can use to select any element in the DOM.
/* Syntax */ jQuery(); $(); // shortcut
/** * Example * * Selects all the links among the descendants of the 'my-class' class */ jQuery('.my-class a'); $('.my-class a');
See more in the jQuery API docs: jQuery() global function.
JavaScript:
/* Syntax */ Document.querySelectorAll();
/* Example */ document.querySelectorAll('.my-class a');
See more in the DOM API docs: .querySelectorAll() method.
2. Select First Element
jQuery:
/* Syntax */ .first();
/** * Example * * Selects the first link among the descendants of the 'my-class' class */ $('.my-class a').first();
See more in the jQuery API docs: first() method.
JavaScript:
/* Syntax */ Document.querySelector();
/* Example */ document.querySelector('.my-class a');
See more in the DOM API docs: .querySelector() method.
3. Find Elements
jQuery:
/* Syntax */ .find();
/** * Example * * Find all the span tags that are descendants of links within * the 'my-class' class * * Note: searches for all descendants not just for children */ $('.my-class a').find('span'); $('.my-class a').find('span').css('color', 'red'); // for testing
See more in the jQuery API docs: .find() method.
JavaScript:
/* Syntax */ // to find the first element (also if there's only one) Document.querySelector(); // to find all elements Document.querySelectorAll();
/** * Example * * At first querySelectorAll() returns a NodeList, so we have to loop * through it to find all the span tags we want * * For the sake of testing, I made the selected elements red, * you can find the 'style.color' property below in this cheat sheet */ // finds all '.my-class a' let nodes = document.querySelectorAll('.my-class a'); // loops through all '.my-class a' for (let i = 0; i < nodes.length; i++) { // checks if the individual '.my-class a' element has a // 'span' descendant to avoid 'undefined' error if (nodes[i].querySelector('span')) { // colors span tags that are desdendants of '.my-class a' nodes[i].querySelector('span').style.color = 'red'; } }
See code demo:
See more in the DOM API docs: .querySelector() method, .querySelectorAll() method.
4. Select Children
jQuery:
/* Syntax */ .children(); .children('selector');
/** * Example * * (1) Finds all the children of all '.my-class a' elements on the age * * (2) Finds all the 'span' elements that are the children of * any '.my-class a' element on the page * * Note: searches only for children (first-level of descendants) */ $('.my-class a').children(); $('.my-class a').children('span'); $('.my-class a').children('span').css('color', 'blue'); // for testing
See more in the jQuery API docs: .children() method.
JavaScript:
/* Syntax */ ParentNode.children;
/** * Example * * 2nd example of the jQuery version above, plus makes the selected span * tags blue for the sake of easy testing * * for 1st example, only leave out the if check at the end (we need this * because the JS version is not a method but a property, so we * need to check which children are 'span') * */ // selects all the elements with 'my-class a' on the page let items = document.querySelectorAll('.my-class a'); // loops through all the elements with '.my-class a' for (let i = 0; i < items.length; i++) { // finds the children of the current '.my-class a' element let kids = items[i].children; // loops through the children of the current '.my-class a' element for (let j = 0; j < kids.length; j++) { // checks if the child element is a span tag if (kids[j].tagName == 'SPAN') { kids[j].style.color = 'blue'; } } }
See test code:
See more in the DOM API docs: .children property – remember that while the JavaScript version is a property, the jQuery version was a method with a parenthesis after it.
5. Select Parent
jQuery:
/* Syntax */ .parent();
/** * Example * * Selects the parent elements of ALL elements with 'my-class a' * on the page */ $('.my-class a');
See more in the jQuery API docs: .parent() method
JavaScript:
/* Syntax */ Node.parentNode;
/** * Example * * Selects the parent of the FIRST element with 'my-class a' on the page * (for the sake of less repetition) * * For looping through all '.my-class a' elements, use the looping * solution and querySelectorAll() from the two examples above. */ let item = document.querySelector('.my-class a'); item.parentNode;
See more in the DOM API docs: .parentNode property.
6. Select Siblings
jQuery:
/* Syntax */ .siblings();
/** * Example * * Selects the siblings of ALL elements with the 'find-siblings' * class on the page */ $('.find-siblings').siblings();
See more in the jQuery API docs: .siblings() method.
JavaScript:
/* Syntax */ Node.parentNode.querySelectorAll(":not(#elem)");
/** * Example * * Selects the siblings of the FIRST element with the * 'find-siblings' class * * For looping through all 'find-siblings' elements, see examples #3 and #4 * * the ':scope' pseudoclass is necessary for preventing the child * elements of 'item' from being selected (otherwise querySelectorAll() * searches through all descendants of 'item', with ':scope >' it loops * through just the first level) * */ let item = document.querySelector('.find-siblings'); let siblings = item.parentNode.querySelectorAll(':scope > :not(.find-siblings)');
See test demo:
See more in the DOM API docs: .parentNode property, .querySelectorAll() method, :scope pseudo-class (see 'Direct Children' section).
7. Select Next Sibling
jQuery:
/* Syntax */ .next();
/** * Example * * Selects the next siblings of all elements with 'my-class a' * on the page */ $('.my-class a').next();
See more in the jQuery API docs: .next() method.
JavaScript:
/* Syntax */ NonDocumentTypeChildNode.nextElementSibling;
/** * Example * * For declaring the 'item' variable by selecting elements with * 'my-class a' on the page, see examples #3, #4, #5 */ item.nextElementSibling;
See more in the DOM API docs: .nextElementSibling property.
8. Select Previous Sibling
jQuery:
/* Syntax */ .prev();
/** * Example * * Selects the previous siblings of all elements with 'my-class a' * on the page */ $('.my-class a').prev();
See more in the jQuery API docs: .prev() method.
JavaScript:
/* Syntax */ NonDocumentTypeChildNode.previousElementSibling;
/** * Example * * For declaring the 'item' variable by selecting elements with * 'my-class a' on the page, see examples examples #3, #4, #5 */ item.previousElementSibling;
See more in the DOM API docs: .previousElementSibling property.
9. Find the Closest Matching Element
jQuery:
/* Syntax */ .closest('selector-name');
/** * Example * * Checks each 'my-class' element and all of its parent elements, * then returns the first paragraph element it finds. */ $('.my-class').closest('p');
See more in the jQuery API docs: .closest() method.
JavaScript:
/* Syntax */ Element.closest();
/** Example * * Checks item and all of its parents and returns the first div it finds * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.closest('div');
See test demo:
See more in the DOM API docs: .closest() method.
10. Add Class
jQuery:
/* Syntax */ .addClass();
/** * Example * * Adds the 'second-class' class to every 'my-class' element * */ $('.my-class').addClass('second-class');
See more in the jQuery API docs: .addClass() method.
JavaScript:
/* Syntax */ Element.classList.add();
/** * Example * * For declaring the 'item' variable by selecting elements with 'my-class' * on the page, see examples examples #3, #4, #5 */ item.classList.add('second-class');
See more in the DOM API docs: .classList property and .add() method.
11. Remove Class
jQuery:
/* Syntax */ .removeClass();
/** * Example * * (1) Removes the 'second-class' class from every 'my-class' element * * (2) Removes 'second-class', then add 'third-class' to * every 'my-class' element */ $('.my-class').removeClass('second-class'); $('.my-class').removeClass('second-class').addClass('third-class');
See more in the jQuery API docs: .removeClass() method.
JavaScript:
/* Syntax */ Element.classList.remove();
/** * Example * * For declaring the 'item' variable by selecting elements with 'my-class' * on the page, see examples examples #3, #4, #5 */ item.classList.remove('second-class'); // To use it together with add(), you need two separate statements item.classList.remove('second-class'); item.classList.add('third-class');
See more in the DOM API docs: .classList property, .remove() method.
12. Toggle Class
jQuery:
/* Syntax */ .toggleClass();
/** Example * * Adds the 'active' class to elements with 'my-class' if they don' have it * remove it if they have it * */ $('.my-class').toggleClass('active');
See more in the jQuery API docs: .toggleClass() method.
JavaScript:
/* Syntax */ Element.classList.toggle();
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.classList.toggle('active');
See more in the DOM API docs: .classList property, .toggle() method.
13. Has Class
jQuery:
/* Syntax */ .hasClass();
/** * Example * * Checks if any element with 'my-class' has the 'active' class * * Returns true or false * * If there's at least one element with 'active' it's true, * otherwise false. * */ $('.my-class').hasClass('active');
See more in the jQuery API docs: .hasClass() method.
JavaScript:
/* Syntax */ Element.classList.contains();
/** * Example * * Similar to the jQuery version, this one also checks if any element * in the whole classList has the 'active' class * * If at least one element has 'active', it's true, otherwise false * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.classList.contains('active');
See more in the DOM API docs: .classList property, .contains() method.
14. Get Attribute
jQuery:
/* Syntax */ .attr('attr-name');
/** * Example * * Returns the value of the href property of the FIRST occurrence of * an element with 'my-class' * */ $('.my-class').attr('href');
See more in the jQuery API docs: .attr() method.
JavaScript:
/* Syntax */ Element.getAttribute('attr-name');
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.getAttribute('href');
See more in the DOM API docs: .getAttribute() method.
15. Set Attribute
jQuery:
/* Syntax */ .attr('attr-name', value);
/** * Example * * Sets the value of the href property for ALL contact links that * have the 'contact-link' class * */ $('.contact-link').attr('href', 'contact.html');
See more in jQuery API docs: .attr() method (you need to use the same .attr()
method as for getting an attribute value, but with two parameters instead of one).
JavaScript:
/* Syntax */ Element.setAttribute();
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.setAttribute('href', 'contact.html');
See more in the DOM API docs: .setAttribute() method.
16. Remove Attribute
jQuery:
/* Syntax */ .removeAttr('attr-name');
/** * Example * * Removes 'target' attributes from contact links */ $('.contact-link').removeAttr('target');
See more in the jQuery API docs: .removeAttr() method.
JavaScript:
/* Syntax */ Element.removeAttribute();
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.removeAttribute('target');
See more in the DOM API docs: .removeAttribute() method.
17. Append a New Child Element
jQuery:
/* Syntax */ .append('html-string');
/** * Example * * Appends an extra list element to the end of every ordered list on the page * */ $("ol").append("<li>");
See more in the jQuery API docs: .append() method.
JavaScript:
/* Syntax */ Node.appendChild();
/** * Example * * For declaring the 'ol' variable, see examples #3, #4, #5 */ ol.appendChild(document.createElement("li"));
See more in the DOM API docs: .appendChild() method and .createElement() method.
18. Prepend a New Child Element
jQuery:
/* Syntax */ .prepend('html-string');
/** * Example * * Prepends an extra list element to the beginning of every ordered list on the page * */ $("ol").prepend("<li>");
See more in the jQuery API docs: .prepend() method.
JavaScript:
/* Syntax */ Node.insertBefore();
/** * Example * * For declaring the 'ol' variable, see examples #3, #4, #5 */ ol.insertBefore(document.createElement("li"), ol.firstChild);
See test code (for both appending and prepending a child node):
See more in the DOM API docs: .insertBefore() method, .createElement() method, and firstChild property.
19. Remove All Child Nodes
jQuery:
/* Syntax */ .empty();
/** * Example * * Removes all child nodes (HTML + text) of each element * that has 'my-class' */ $('.my-class').empty();
See more in the jQuery API docs: .empty() method.
JavaScript:
/* Syntax */ Element.replaceChildren();
/** * Example * * Empties the 'item' node of all of its children * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.replaceChildren();
See more in the DOM API docs: .replaceChildren() method.
20. Get or Set HTML Content
jQuery:
/* Syntax */ .html(); .html('html-string');
/** * Example * * (1) Gets the HTML content of the FIRST element that matches 'my-class' * * (2) Sets/resets the HTML content of EACH element that matches 'my-class' * */ $('.my-class').html(); $('.my-class').html('<em>Hello</em>');
See more in the jQuery API docs: .html() method.
JavaScript:
/* Syntax */ Element.innerHTML;
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.innerHTML; // gets the value item.innerHTML = '<em>Hello</em>'; // sets the value
See more in the DOM API docs: .innerHTML property.
21. Replace an Element with New HTML Content
jQuery:
/* Syntax */ .replaceWith('new-html-content');
/** * Example * * * Selects a heading, then replaces the full HTML content, * including the parent element */ $('#my-heading').replaceWith('<h3 id="my-heading">New Heading</h3>');
See more in the jQuery API docs: .replaceWith() method.
JavaScript:
/* Syntax */ Element.outerHTML = 'new HTML content';
/** * Example * * Replaces the full HTML content, including the parent element * */ let item = document.querySelector('#my-heading'); item.outerHTML = '<h3 id="my-new-heading">New Subheading</h3>';
See more in the DOM API docs: .outerHTML property.
22. Get or Set CSS Property
jQuery:
/* Syntax */ .css('property-name'); .css('property-name', value);
/** * Example * * (1) Gets the 'color' value of the FIRST element * that has 'my-class' * * (2) Sets the 'color' value to 'white' for EVERY element that has * 'my-class' */ $('.my-class').css('color'); $('.my-class').css('color', 'white');
See more in the jQuery API docs: .css() method.
JavaScript:
/* Syntax */ ElementCSSInlineStyle.style.{propertyName};
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.style.color; // getting value item.style.color = 'white'; // setting value
See more in the DOM API docs: .style property and CSS Properties Reference (for the JavaScript names of CSS properties).
23. Get or Set Text Content of an Element and All of Its Descendants
jQuery:
/* Syntax */ .text(); .text('text');
/** * Example * * (1) Gets the text content of the FIRST element (and all of its descendants) that matches 'my-class' * * (2) Sets/resets the text content of EACH element that matches 'my-class' * */ $('.my-class').text(); $('.my-class').text('<em>Hello</em>');
See more in the jQuery API docs: .text() method.
JavaScript:
/* Syntax */ Element.textContent;
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.textContent; // gets the value item.textContent = '<em>Hello</em>'; // sets the value
See more in the DOM API docs: .textContent property.
24. Get or Set Input Values
jQuery:
/* Syntax */ .val(); .val(val);
/** * Example * * (1) Gets the value of the input with the 'name' name * * (2) Sets/resets the value of the input with the 'name' name * */ $('input[name=name]').val(); $('input[name=name]').val('Marilyn Monroe');
See more in the jQuery API docs: .val() method.
JavaScript:
/* Syntax */ HTMLInputElement.value;
/** * Example * * For declaring the 'input' variable, see examples #3, #4, #5 */ input.value; // gets the value input.value = 'Marilyn Monroe'; // sets the value
See more in the DOM API docs: .value property (in the list of ''Properties that apply to any type of input element that is not hidden").
25. Hide Element
jQuery:
/* Syntax */ .hide();
/** * Example * * Hides all elements with 'my-class' */ $('.my-class').hide();
See more in the jQuery API docs: .hide() method.
JavaScript:
/* Syntax */ ElementCSSInlineStyle.style.display = 'none';
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.style.display = 'none';
See more in the DOM API docs: .style property.
26. Show Element
jQuery:
/* Syntax */ .show();
/** * Example * * Displays all elements with 'my-class' */ $('.my-class').show()
See more in the jQuery API docs: .show() method.
JavaScript:
/* Syntax */ ElementCSSInlineStyle.style.display = '';
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.style.display = ''; // resets default item.style.display = 'block'; // sets display as block item.style.display = 'flex'; // sets display as flex
See more in the DOM API docs: .style property.
27. Add Event Listener
jQuery:
/* Syntax */ .on();
/** * Example * * Adds or removes the 'active' class to/from all elements with * '.submenu' when #toggle is clicked */ $('#toggle').on('click', function(){ $('.submenu').toggleClass('active'); });
See more in the jQuery API docs: .on() method
JavaScript:
/* Syntax */ EventTarget.addEventListener('event', functionName);
/** * Example * * The code below only selects the FIRST element with the * 'submenu' class. * * To select all submenus, use the 'for' loop in Example #3 and #4 */ let toggle = document.querySelector("#toggle"); let submenu = document.querySelector(".submenu"); toggle.addEventListener('click', function() { submenu.classList.toggle('active'); });
See test code:
See more in the DOM API docs: .addEventListener() method and DOM Event Reference.
28. Remove Event Listener
jQuery:
/* Syntax */ .off();
/** * Example * * Removes the listed event handler when #toggle is clicked */ $('#toggle').off('click', function(){ $('.submenu').toggleClass('active'); });
See more in the jQuery API docs: .off() method.
JavaScript:
/* Syntax */ EventTarget.removeEventListener('event', functionName);
/** * Example * * The code below only selects the FIRST element with the * 'submenu' class. * * To select all submenus, use the 'for' loop in Example #3 and #4 */ let toggle = document.querySelector("#toggle"); let submenu = document.querySelector(".submenu"); toggle.removeEventListener('click', function() { submenu.classList.toggle('active'); });
See more in the DOM API docs: .removeEventListener() method and DOM Event Reference.
29. Execute a Function When the DOM Is Ready
jQuery:
/** * Syntax * * This is the jQuery 3 version of $(document).ready(function(){}); * which is now deprecated. */ $(function() { // event handler });
/** * Example * * Event: The DOM (document) is fully loaded * * Action triggered by this event: Message in the console */ $(function() { console.log('The DOM is ready!'); });
See more in the jQuery API docs: .ready() method.
JavaScript:
/* Syntax version 01 */ if(document.readyState === 'complete' || (document.readyState !== 'loading')) { // event handler } else { document.addEventListener('DOMContentLoaded', function() { // event handler }); } /** * Syntax version 02 - you can store the event handler * in a custom callback function */ let handler() = function(){ // event handler }; if(document.readyState === 'complete' || (document.readyState !== 'loading')) { handler() } else { document.addEventListener('DOMContentLoaded', handler); }
/** Example * * When the document is fully loaded, a message is logged to the console. */ // version 01 if(document.readyState === 'complete' || (document.readyState !== 'loading')) { console.log('The DOM is ready!'); } else { document.addEventListener('DOMContentLoaded', function() { console.log('The DOM is ready!'); }); } // version 02 // (with a custom 'logMessage' function that holds the event handler) let logMessage = function(){ console.log('The DOM is ready!'); }; if(document.readyState === 'complete' || (document.readyState !== 'loading')) { logMessage(); } else { document.addEventListener('DOMContentLoaded', logMessage); }
See more in the DOM API docs: readyState property, addEventListener() method.
30. Loop Through an Object, Array, or Collection
jQuery:
/* Syntax */ .each();
/** * Example * * Finds each paragraph and turns them yellow */ $('p').each(function() { $(this).css('color', '#fbdf00'); });
See more in the jQuery API docs: .each() method.
JavaScript:
/* Syntax */ NodeList.prototype.forEach(); // we'll use this in the example below Array.prototype.forEach(); Map.prototype.forEach(); Set.prototype.forEach();
/** * Example * * v1 turns red all paragraphs on the page * * v2 turns green all list items on the page */ // v1 (inline callback function syntax) let itemsV1 = document.querySelectorAll('p'); itemsV1.forEach( function(item) { item.style.color = 'white'; } ); // v2 (arrow function syntax) let itemsV2 = document.querySelectorAll('li'); itemsV2.forEach(item => item.style.color = '#fbdf00');
See test demo:
See more in the DOM API docs: .foreach() methods of the NodeList, Array, Map, and Set interfaces.
Next Steps
This jQuery to JavaScript cheat sheet includes the most important functionalities that you’ll need for building a website. By familiarizing yourself with these properties and methods, you can make the jump from jQuery to JavaScript. However, you’ll likely need to know more if you want to build more complex functionality.
There are two other resources I’d recommend to find the jQuery to JavaScript equivalent you need: the You Might Not Need jQuery website and Jack O’Connor’s jQuery-to-JavaScript repo on GitHub.
Even though I used the classic for
loop to loop through querySelectorAll()
matches, modern JavaScript provides you with other options, too — Chris Coyier shows some of them in this article about JavaScript loops.
Experimenting and creating your own code snippets can also help a lot if you want to confidently use native JavaScript and the DOM API in your everyday workflow.
Learn More JavaScript with Tuts+
If you’re just starting out with JavaScript these Tuts+ courses will put you in the right direction:
This content originally appeared on Envato Tuts+ Tutorials and was authored by Anna Monus
Anna Monus | Sciencx (2021-04-07T09:08:59+00:00) Essential Cheat Sheet: Convert jQuery to JavaScript. Retrieved from https://www.scien.cx/2021/04/07/essential-cheat-sheet-convert-jquery-to-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.