Getting A Class From a DOM Element

Lately, if I am searching for a way to do something in Javascript the only results I am getting ways of doing the procedure using jQuery. While, its true jQuery is pretty much the de facto standard for writing JavaScript anymore, understanding the underlying technology is a must. As well as alot of times, I don’t need to load jQuery on the page just to get a DOM Element or its class.

So I recently went looking on how to get class from element in JavaScript. Turns out most of the results were for getting elements by class name, rather than actually getting the class of the element I already had.

Here is how you get a class name from an Element using JavaScript.

	document.getElementById("tag_cloud-2").className

	Output:
		"sidebaritem widget_tag_cloud"

Now, that wasn’t so hard. Lets take a look at a performance test: jQuery versus getting a className.

Here is the setup for the test

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

<div class="wrapper">
	<div class="innerWrapper">
		<div id="getMe" class="button">
			<a href="javascript:void(0)" id="button" class="buttonRef">
				<span class="buttonText">Text</span>
			</a>
		</div>
	</div>
</div>

<script>
	var jElem = $("#getMe");
	var dElem = document.getElementById("getMe");
</script>

Here are the tests:

1. jQuery - get Element + get Class   $("#getMe").attr('class');
2. GET DOM ELEM + get Class           document.getElementById("getMe").className;
3. jQuery get Class                   jElem.attr('class');
4. DOM get class                      dElem.className;

Chrome 11 Results

In Chrome using a cached element, getting the classname is 48x faster than using jQuery.
In Chrome getting the element and then getting the classname is 25x faster than using jQuery.

FF 4.0 Results

In FF using a cached element, getting the classname is 65x faster than using jQuery.
In FF getting the element and then getting the classname is 83x faster than using jQuery.

Safari 5.0 Results

In Safari using a cached element, getting the classname is 30x faster than using jQuery.
In Safari getting the element and then getting the classname is 35x faster than using jQuery.

Summary

Whenever possible, using the browsers built in methods will always be faster, and just because you have a library available doesn’t mean you should be using it for every DOM query. The speed advantage alone should dictate which methods of the library you are using and when.

2 thoughts on “Getting A Class From a DOM Element”

Leave a Reply to kimball Cancel reply

Your email address will not be published. Required fields are marked *