- you need to support IE6/7/8 (remember you can’t migrate to jQuery 2.0), or
- without jQuery, you’d spend longer writing a jQuery-like library than developing your application.
DOM Selectors
jQuery permits DOM node selection using CSS selector syntax, e.g.// find all paragraphs with the class "summary" in the article with ID "first"
var n = $("article#first p.summary");
The native equivalent:
var n = document.querySelectorAll("article#first p.summary");
document.querySelectorAll
is implemented in all modern browsers and IE8 (although that only supports CSS2.1 selectors). jQuery has additional support for more advanced selectors but, for the most part, it’ll be running document.querySelectorAll
inside the $()
wrapper.
Native JavaScript also provides four alternatives which will almost certainly be faster than querySelectorAll if you can use them:
document.querySelector(selector)
— fetches the first matching node onlydocument.getElementById(idname)
— fetches a single node by its ID namedocument.getElementsByTagName(tagname)
— fetches nodes matching an element (e.g. h1, p, strong, etc).document.getElementsByClassName(class)
— fetches nodes with a specific class name
var n = document.getElementById("first");
var p = n.getElementsByTagName("p");
Let’s do some testing. I wrote a small selection of scripts to retrieve all the comment nodes from my Do You Really Need jQuery? article 10,000 times. The result:
code | time |
---|---|
|
4,649 ms |
|
3,437 ms |
|
1,362 ms |
|
1,168 ms |
|
107 ms |
|
75 ms |
querySelectorAll
.
DOM Manipulation
jQuery offers several methods for adding further content to the DOM, e.g.$("#container").append("<p>more content</p>");
Beneath the surface, jQuery uses the native innerHTML method, e.g.
document.getElementById("container").innerHTML += "<p>more content</p>";
You can also use DOM building techniques. These are safer but rarely faster than innerHTML:
var p = document.createElement("p");
p.appendChild(document.createTextNode("more content");
document.getElementById("container").appendChild(p);
We can also remove all child nodes in jQuery:
$("#container").empty();
The native equivalent using innerHTML:
document.getElementById("container").innerHTML = null;
or a small function:
var c = document.getElementById("container");
while (c.lastChild) c.removeChild(c.lastChild);
Finally, we could remove the whole element from the DOM in jQuery:
$("#container").remove();
or native JavaScript:
var c = document.getElementById("container");
c.parentNode.removeChild(c);
Scalable Vector Graphics
The core jQuery library has been developed to work with the current document. SVGs also have a DOM, but jQuery does not offer direct manipulation of these objects because it’s normally necessary to use methods such ascreateElementNS
and getAttributeNS
. It can be made to work and several plug-ins are available, but it will be more efficient to roll your own code or use a specialized SVG library such as Raphaël or svg.js
.
HTML5 Forms
Even the most basic web application will have a form or two. You should always validate user data server-side but, ideally, you’ll supplement it with client-side validation to capture errors before the form is submitted. Client-side validation is straight-forward:- You run a function when the form is submitted.
- If any issues are encountered, you halt the submission and show an error.
<input type="email" name="email" required="required" />
There’s no need for additional JavaScript or jQuery code unless you require a little more sophistication such as comparing two or more fields or showing custom error messages.
Older browsers (including IE9 and below) do not understand the new types and will revert to standard textual input fields. Those users will fall back to server-side validation; not a great experience but you can apply a shim or hope those people see the light and upgrade.
In my next article, we’ll examine native CSS class manipulation and animation.
Frequently Asked Questions about jQuery and Raw JavaScript
What are the main differences between jQuery and raw JavaScript?
jQuery is a JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. On the other hand, raw JavaScript, also known as Vanilla JavaScript, is the pure form of JavaScript without any additional libraries. jQuery provides a simpler and more convenient syntax, which makes it easier for beginners to use. However, raw JavaScript is more powerful and flexible, allowing for more complex and customized solutions.
Why would I choose raw JavaScript over jQuery?
While jQuery simplifies many tasks, it comes with a cost. It’s a large library that can slow down your website’s performance. If you’re working on a project that requires high performance or you want to have full control over your code, raw JavaScript might be a better choice. Additionally, understanding raw JavaScript can make you a better developer as it deepens your understanding of the language.
Is jQuery still relevant today?
Yes, jQuery is still relevant today. Despite the rise of modern JavaScript frameworks like React, Angular, and Vue.js, jQuery remains popular due to its simplicity and wide browser compatibility. It’s especially useful for smaller projects or for adding simple interactive elements to websites.
Can I use jQuery and raw JavaScript together in a project?
Yes, you can use jQuery and raw JavaScript together in a project. jQuery is built on top of raw JavaScript, so you can freely mix jQuery and raw JavaScript code. However, it’s generally recommended to stick to one or the other for consistency and readability.
What are the performance differences between jQuery and raw JavaScript?
Raw JavaScript generally performs better than jQuery because it doesn’t have the overhead of a library. However, the performance difference is usually negligible for most web applications. The choice between jQuery and raw JavaScript should be based more on your project requirements and personal preference.
How can I transition from jQuery to raw JavaScript?
Transitioning from jQuery to raw JavaScript involves learning the raw JavaScript equivalents of jQuery methods. There are many resources available online that can help you with this. It’s also important to understand the JavaScript fundamentals, such as variables, functions, loops, and events.
What are some common tasks that are easier in jQuery than in raw JavaScript?
Some common tasks that are easier in jQuery include selecting elements, handling events, creating animations, and making Ajax requests. jQuery provides simple and intuitive methods for these tasks, which can save you time and reduce the complexity of your code.
What are some advantages of using raw JavaScript?
Some advantages of using raw JavaScript include better performance, more control over your code, and a deeper understanding of JavaScript. It also doesn’t require you to load any external libraries, which can improve your website’s load time.
Is it necessary to learn jQuery if I already know raw JavaScript?
It’s not necessary to learn jQuery if you already know raw JavaScript, but it can be beneficial. jQuery can simplify many tasks and make your code more readable. It’s also widely used in the industry, so knowing jQuery can be a plus when looking for a job.
Can I replace jQuery with raw JavaScript in an existing project?
Yes, you can replace jQuery with raw JavaScript in an existing project, but it can be a complex task. You’ll need to rewrite all the jQuery code in raw JavaScript, which can take a lot of time and effort. It’s usually recommended to do this gradually, starting with the simplest parts of your code.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.