Getting to Know the JavaScript element.classList Object

Object-Oriented JavaScript

JavaScript LogoNative JavaScript provides a way to access and manipulate all of the CSS classes that are assigned to an HTML element.

The JavaScript element.classList object is an instance of the JavaScript DOMTokenList object. It exposes one property and a number of methods that allow you to work with CSS classes that are assigned to an HTML element.

While it has been supported for some time by all major browsers, Microsoft Internet Explorer has, unfortunately, ignored JavaScript’s element.classList object until very recently (what a big surprise). If you need to support IE9 and below (and of course you do), then all bets are off. Bummer. That said, this object is nonetheless a super-helpful feature that makes CSS class manipulation a snap.

But what about jQuery?

There is no doubt that the jQuery methods hasClass(), addClass(), removeClass() and toggleClass() are all fantastic, but there ain’t nothin’ goin’ on under the hood that you can’t do yourself. And what is under the hood is tedious stuff like this:

This kind of code will soon join the ranks of the eight-track cassette and pagers. While that is the current reality of cross-browser CSS class list manipulation, the fact is that native JavaScript is always evolving, and as soon as Internet Explorer 10 becomes the IE standard, the JavaScript element.classList object will be yet another native JS tool to tuck into your belt.

The length Property

Even though the element.classList object is not an array, it is “array-like” in that it has a “length” property, and each CSS class name is represented by a numerically indexed property whose value is the name of that class (a string). This is super-helpful if you want to enumerate the classes that are members of this object. You could certainly grab an individual member’s value using bracket-notation: element.classList[0], a “for” loop, or the item() method, which is discussed next.

The JsFiddle link below demonstrates the classList object’s length property. The class “bar” is toggled when you click the element specified. On each click, the classList object’s length property is shown. Since a class is toggled, that length value changes with each click, which helps to demonstrate the dynamic nature of this property. Keep in mind that like any JavaScript array, the length property’s value will always be one higher than the index of the last element.

Here is the JsFiddle.net link for the classList object’s “length” property : http://jsfiddle.net/BmFZc/

The item() Method

The item() method allows you to reference a specific class name in the collection of class names. When you pass an integer to this method, it returns a string representation of the class name that matches that index. So keep in mind that this collection is zero-based. In the first JsFiddle link below, we manually reference a number of classes in the class list, using the item() method. In the second JsFiddle link below, we use a “for” loop to accomplish the same task.

Here is the JsFiddle.net link for the item() method: http://jsfiddle.net/N88x9/

Here is a second JsFiddle.net link for the item() method: http://jsfiddle.net/WE7gc/

The add() method

As you might expect, the add() method adds a class to the element’s class list. In the JsFiddle link below, you can see that the class “bar” is added to the element’s class list because the element’s appearance changes dramatically, as per the CSS that is specified.

Here is the JsFiddle.net link for the add() method: http://jsfiddle.net/uzMAx/

The remove() Method

In the manner opposite to the add() method, the remove() method removes the specified class from the element’s class list. Much like the example for the add() method, you can see that the class “bar” is removed from the element’s class list because the element’s appearance changes dramatically, as per the CSS that is specified.

Here is the JsFiddle.net link for the remove() method: http://jsfiddle.net/4h7m4/

The toggle() Method

The toggle() method will check to see if the element already has the specified class. If not, then it adds the class. If it does have the class, then it removes it. Depending on the scenario, this can minimize redundant code.

Here is the JsFiddle.net link for the toggle() method: http://jsfiddle.net/wWfNf/

The contains() Method

You can check to see if an element already has a class by using the contains() method. When you pass it a string name representing the class that you would like to check for, it returns true or false, indicating whether or not the element has the class you provided.

Here is the JsFiddle.net link for the contains() method: http://jsfiddle.net/wWfNf/

The toString() Method

The toString() Method simply returns a space-separated list of the classes that are applied to that element.

Here is the JsFiddle.net link for the toString() method: http://jsfiddle.net/GqzD5/

Summary

In this article we learned about JavaScript’s element.classList object. We demonstrated that while not exactly a JavaScript array, it is an “array-like” object with a length property, and some useful methods that allow you to work with the CSS classes that are assigned to an HTML element.

Helpful Links for the JavaScript element.classList object

https://developer.mozilla.org/en-US/docs/Web/API/element.classList

http://blog.alexanderdickson.com/manipulating-classes-with-javascript

http://tiffanybbrown.com/2011/08/15/class-manipulation-with-classlist/

How to Turn the Query String Into a JavaScript Object

Object-Oriented JavaScript

JavaScript LogoIt is fairly common for any front-end web developer to examine the query string. If jQuery has taught us anything, that would be the power of abstraction: create functionality once, and then use that functionality as a tool over and over, as needed.

When working with the query string, it is usually best to grab it once, and then be done with that task. This will prove substantially helpful if you need to refer to the query string more than once in your code. If we do the work once, and do it right, then we have created a nice little tool that we can use over and over throughout our code.

So perhaps the best way to accomplish this task is to turn the query string into a JavaScript object. Simple stuff here. Let’s lay out our plan of attack:

  1. Get a reference to the Query String
  2. Chop off the question mark (we don’t need that)
  3. Turn the key/values into elements of an array
  4. Turn each key/value pair into a little two-element array
  5. Populate our object with each key/value as a propertyName / propertyValue
  6. We’re done!

So okay, let’s get to work.

Example # 1

In Example # 1 we have the raw and basic code needed to accomplish our task. I won’t go into any detail here. I just wanted to illustrate that the actual code needed is fairly minimal. So, if you run this code in your JavaScript console, and you have appended a query string to the page URL, you should see the object we created in the console.

Example # 2

In Example # 2, we expanded out the code with comments to make it easier to follow along. I won’t replicate each comment, but from a high-level perspective, here are the steps we take:

  1. Declare our variables at the top of the function (just good form)
  2. Get a reference to the query string, and chop off the question mark (i.e. omit “?”)
  3. Turn the query string into an array, using “&” as a delimiter
  4. Take that array, and split each element into a sub-array, using “=” as a delimiter
  5. That sub-array will always be a two-element array because on the left of the “=” is a key, and on the right side of it is a value
  6. Turn those two sub-array elements into a new “property / value” pair for our return object
  7. Repeat the last two steps for each sub array that was generated, by splitting the first array at “&”
  8. Now return our new object

Example # 3

In Example # 3, we added functionality that allows us to inject the values of our new object into the DOM. We use a for-in loop to iterate over the properties of our object. For each iteration of that loop, we inject a new LI element, with the appropriate markup for presentation. Note how we are using the variable “prop” and we also make a reference to “queryObject[prop]” which holds the value of the current property over which we are iterating.

Example # 4

In Example # 4, we have the full source code for our completed working example.

Here is the link to our full working example: http://examples.kevinchisholm.com/javascript/query-string/to-object/?fname=alfred&lname=newman&acctNum=010203&salesRegion=EastCoast&company=MadMagazine

Summary

In this article, we took at look at one way in which you can turn the query string into a JavaScript object. We learned how to get a reference to the query string, omit the question mark, turn the key/value pairs into an array, and then work with each element of that array to turn them into properties of our new object. We also learned how to inspect our new object and inject it into the DOM as markup.

Helpful Links for working with the Query String using JavaScript

http://en.wikipedia.org/wiki/Query_string
http://joncom.be/code/javascript-querystring-values/
http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
http://stackoverflow.com/questions/647259/javascript-query-string

JavaScript Interview Questions: Object-Oriented JavaScript

Object-Oriented JavaScript

QUESTION:

True or False: the terms “scope” and “context” refer to the same thing in JavaScript.

Click for Answer

QUESTION:

If you omit the “var” keyword when creating a variable in a function, it becomes a property of what object?

Click for Answer

QUESTION:

How do you determine if a JavaScript instance object was created from a specific constructor or not?

Click for Answer

QUESTION:

True or False: Once you create an object, you can add, remove or change properties of that object at any time.

Click for Answer

QUESTION:

True or False: You can only instantiate a JavaScript constructor function once.

Click for Answer

QUESTION:

When you create a function inside of a method, what does the “this” keyword refer to when used in that function?

Click for Answer

QUESTION:

Name two ways two change the context of a JavaScript method

Click for Answer

QUESTION:

Can a JavaScript constructor return a primitive value (e.g. a number or a string)?

Click for Answer

QUESTION:

In JavaScript, are objects passed by reference or by value?

Click for Answer

QUESTION:

What is the difference between a constructor function and a non-constructor function with respect to the word “this”

Click for Answer

QUESTION:

What is the name of the property that allows you to add properties and methods to an object, as well as every object that inherits from it?

Click for Answer

QUESTION:

True or False: An object literal can be used to create private variables.

Click for Answer

QUESTION:

What is the name of the object that refers to the application used to view a web page?

Click for Answer

QUESTION:

True or False: The object returned by the document.getElementsByTagName() method is an array.

Click for Answer


QUESTION:

Which object.property combination provides a reference to the protocol used to view the current web page?

Click for Answer

QUESTION:

Given the below code, what line of JavaScript would allow foo.getColor to return the value of foo.color, without using the word “foo”?

Click for Answer (+)

QUESTION:

What is the difference between using dot notation and bracket notation when accessing an object’s property?

Click for Answer (+)

QUESTION:

What is important to remember about the last property’s value in a JavaScript object literal?

Click for Answer

QUESTION:

Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?

Click for Answer

QUESTION:

Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?

Click for Answer

QUESTION:

What are two ways in which the variable “foo” can be assigned to an empty object?

Click for Answer

QUESTION:

True or False: When you create an object literal, you must first instantiate the Object() constructor.

Click for Answer

QUESTION:

When using the addEventListener() method to create a click-handler for a DOM element, what is the value of “this” inside of the callback you specify?.

Click for Answer

QUESTION:

True or False: A JavaScript array is not an object

Click for Answer

QUESTION:

If a string is a primitive value, why does it have a split() method?

Click for Answer

QUESTION:

True or False: A function can have its own properties and methods.

Click for Answer