Native JavaScript Equivalents of jQuery Methods: CSS and Animation

Share this article

Do You Really Need jQuery?
Sometimes — especially if you want to support IE6/7/8 using jQuery 1.x. However, modern browser APIs now provide much of the functionality we take for granted in jQuery. In this article, we’re going to look at methods related to CSS.

Class Manipulation

One of the most common jQuery tasks is applying a class to a specific element:
$("#myelement").addClass("myclass");
We can achieve the same thing in native JavaScript:
document.getElementById("myelement").className = "myclass";
This isn’t quite the whole story:
  1. jQuery can apply the class to any number of nodes.
  2. jQuery appends the new class to existing class definitions, but the native example will overwrite them.
In native JavaScript, the className property is simply a string. We therefore need a function to replicate how jQuery works, e.g.
function addClass(node, class) {
	if (!node.length) node = [node];
	for (var n = 0, m = node.length; n < m; n++) {
		if ((" " + node[n].className + " ").indexOf(" "+class+" ") >= 0) {
			node.className += " " + class;
		}
	}
}
// apply myclass to all nodes
addClass(document.getElementById("myelement"), "myclass");
While this code is smaller and faster than jQuery, we’re replicating what’s already available in the library — there’s little point. Fortunately, modern browsers now offer a new classList property which implements a DOMTokenList — an array-like collection of all classes applied to a node. The following properties are available:
  • length — the number of class names applied
  • item(index) — the class name at a specific index
  • contains(class) — returns true if a node has that class applied
  • add(class) — applies a new class to the node
  • remove(class) — removes a class from the node
  • toggle(class) — removes or adds a class if it’s applied or not applied respectively
We can use this in preference to the clunkier className property:
document.getElementById("myelement").classList.add("myclass");
classList is supported by most browsers except IE9. Fortunately, a couple of shims are available which could be conditionally loaded in that browser.

Style Manipulation

jQuery provides a number of methods to apply specific styles, e.g.
$("#myelement").css({
	color: "#c00",
	backgroundColor: "#eee",
	width: "200px",
	height: "100px",
	borderColor: "#f00"
});
The native equivalent:
var m = document.getElementById("myelement"), c = m.style;
c.color = "#c00";
c.backgroundColor = "#eee";
c.width = "200px";
c.height = "100px";
c.borderColor = "#f00";
Over 10,000 iterations using cached selectors, the jQuery code executed in 6,670ms. Native JavaScript took 330ms — it was 20x faster. Of course, you shouldn’t use either unless a value needs to be calculated in some way. It’s more efficient to define a class of styles in CSS then apply its name to the element.

Animation

jQuery offers various animated effects out of the box including sliding and fading. Native JavaScript can be faster but none of that matters: CSS3 animation trounces both. I was initially skeptical about CSS3 animation. It can never offer fine-grained control (such as stopping an animation after N frames) and trespasses on JavaScript’s behavioral responsibilities. However, the benefits more than outweigh the drawbacks:
  1. CSS3 animation is handled by the browser; it will always be faster than JavaScript execution.
  2. CSS3 animation is easier to use and requires significantly less code.
  3. CSS3 offers effects such as 3D transformations which would be impractical — if not impossible — in JavaScript alone.
IE9 and below won’t show the effects but they can degrade gracefully and IE10 should be the dominant version within a few months
. The CSS3 genie will never go back in the lamp. If you’re still using jQuery or JavaScript for DOM animation in modern browsers, you’re probably wasting your time. That said, JavaScript can be used to react to CSS3 animations when they start, stop or proceed to the next iteration using animationstart, animationend and animationiteration accordingly. For more information, refer to How to Capture CSS3 Animation Events in JavaScript. In my next article, we’ll finish the series by looking at events, Ajax and utility functions.

Frequently Asked Questions (FAQs) about jQuery vs Raw JavaScript and CSS3 Animation

What are the key differences between jQuery and raw JavaScript?

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers. On the other hand, raw JavaScript is a text-based programming language used both on the client-side and server-side that allows you to make web pages interactive. It doesn’t rely on any libraries or frameworks, making it more complex and time-consuming to use than jQuery.

Why would I choose jQuery over raw JavaScript?

jQuery simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation. The jQuery library provides several handy methods for AJAX functionality. Therefore, if you’re looking for a tool that can simplify your web development process, jQuery might be a good choice.

Can CSS3 animations replace jQuery animations?

CSS3 animations are a powerful tool that can replace jQuery animations in some cases. They are generally smoother and perform better than jQuery animations. However, CSS3 animations have limited control compared to jQuery. For instance, you can’t animate to a height of “auto”, or get a callback when the animation completes.

What are CSS logical properties and values?

CSS logical properties and values provide the ability to control layout through logical, rather than physical, direction and dimension mappings. They are a new set of properties that let developers control layout through logical, rather than physical, direction and dimension mappings.

What are the advantages of using raw JavaScript over jQuery?

Raw JavaScript doesn’t rely on any libraries or frameworks, making it more flexible and customizable. It’s also faster and less resource-intensive than jQuery, as it doesn’t need to load any extra resources. Moreover, understanding raw JavaScript can provide a deeper understanding of web development.

What are the key CSS properties I should know?

There are several key CSS properties you should know, including ‘display’, ‘position’, ‘top’, ‘right’, ‘bottom’, ‘left’, ‘width’, ‘height’, ‘margin’, ‘padding’, ‘border’, ‘background’, ‘font’, ‘text’, and ‘box’. Each of these properties has a specific role in styling and positioning elements on a webpage.

How can I animate elements using CSS3?

CSS3 introduces the ‘animation’ property which allows you to animate elements on your webpage. You can control the duration, timing function, delay, iteration count, direction, fill mode, and play state of the animation.

How does jQuery handle events compared to raw JavaScript?

jQuery provides a simple and consistent interface for handling events. It normalizes the event object, which contains event properties and methods, and provides methods to add and remove event handlers on elements.

What are the performance considerations when choosing between jQuery and raw JavaScript?

Raw JavaScript is generally faster and less resource-intensive than jQuery, as it doesn’t need to load any extra resources. However, jQuery can simplify and speed up the development process, which might outweigh the performance benefits of raw JavaScript in some cases.

How can I transition from using jQuery to raw JavaScript?

Transitioning from jQuery to raw JavaScript involves understanding the underlying JavaScript that jQuery abstracts. Start by learning the basics of JavaScript, including variables, data types, functions, control structures, and error handling. Then, learn about the Document Object Model (DOM) and how to manipulate it using JavaScript. Finally, learn about AJAX and how to make AJAX calls using JavaScript.

Craig BucklerCraig Buckler
View Author

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.

animationCSSCSS3HTML5 Dev CenterJavaScriptjQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week