As front end developers or designers, you will have to work with the Document Object Model – also known as the DOM – in your day to day projects. Selecting elements within the DOM and applying dynamic functionality has become more widespread with the improvement of JavaScript techniques in recent years. So we need to have sound knowledge in working with DOM elements in order to avoid conflicts and optimize performance.
jQuery is one of the most popular and commonly used JavaScript libraries, with advanced DOM selection and filtering features. In this article, we are going to look at how we can filter the DOM elements by considering practical scenarios with the help of jQuery.
Let’s get started.
Introduction to IDs, Classes and Data Attributes
Generally, we use HTML element tags, IDs, classes and data attributes for selecting elements within the DOM tree. Most developers are familiar with using HTML tags for selection. But novice developers tend to misuse IDs, classes and data attributes without knowing the exact meaning and the necessity for them in various scenarios. So let’s identify the each of the three options before we move into the practical scenarios.
ID – is used as a unique identifier within the document. So we shouldn’t be using same ID for multiple elements, even though it’s possible. Generally, we use element ID to select elements with jQuery.
Class – is used to style element using CSS. But often classes are used for filtering and selecting elements when an element can’t be filtered using an ID.
Data attributes – are used to define private data for an element. We can have multiple data attributes for a single element to store all the data required for front end functionality.
Practical Scenarios for Using IDs, Classes and Data Attributes
In this section, we are going to look at some of the common use cases for using these filtering and selecting options and how each option suits different scenarios. Practically, there are unlimited possibilities for using these options in different scenarios. So we will be looking at the most important ones, considering the scope of this article.
Scenario 1 – Selecting unique element within the document
This is the most basic and common scenario where we use to select any element. Selecting form values for validation can be considered a good example for such scenario. We use HTML element ID to select elements as shown in the following jQuery code.
$(“#elementID”).val();
It’s important to prevent the duplication of elements with the same ID when using this method.
Scenario 2 – Selecting multiple elements using classes
Generally, we use a class attribute when we want to filter multiple elements within the document. Unlike IDs, we can have multiple elements with the same CSS class. Usually, these type of similar elements are generated through loops.
Assume that we have a list of records containing user data as shown in the following HTML code. We have a Delete button, where users can remove records by clicking.
<table>
<tr><td>Mark</td><td><input type=’button’ class=’user_data’ value=’Delete’ /></td></tr>
<tr><td>John</td><td><input type=’button’ class=’user_data’ value=’Delete’ /></td></tr>
<tr><td>Mike</td><td><input type=’button’ class=’user_data’ value=’Delete’ /></td></tr>
</table>
Now we have multiple instances of similar elements and hence we can’t use ID to filter the exact record. Let’s see how we can filter the rows using the given CSS class.
var rows = $(“.user_data”);
In the preceding code, the rows
variable will have all three rows with the class user_data
. Now let’s see how to remove the row on button click using the class selector.
$(“.user_data”).click(function(){
$(this).parent().parent().remove();
});
In this technique, we traverse through all the matched elements and executes functions on the current item using $(this)
object, which points to the clicked button. This is the most widely used technique for working with multiple elements.
Now let’s look at some of the common mistakes by beginner developers in such scenarios.
-
Using IDs instead of classes
There are many occasions where developers use the same ID inside loops to generate similar HTML code instead of classes. Once the same ID is used, it will only affect the first element. Remaining elements will not work as expected. So make sure to create dynamic IDs within loops and use class name for element selection.
-
Using class name instead of $(this) object
Another mistake made by many beginner developers is the lack of knowledge in the context and the use of the current object. When traversing through multiple elements, we can use jQuery
$(this)
to refer to current element. Many developers use the class name within the loop and hence does not get the desired results. So never use class name within the loop as shown in the following code.
$(“.user_data”).click(function(){
$(“.user_data”).parent().parent().remove();
});
This is a widely used technique for selecting elements and hence it’s important to know how to effectively use this technique. CSS classes are used for styling purposes. But here we are using them for element selection purposes. Using CSS classes for selection purposes is not the best technique and sometimes it can cause conflicts in your layouts. For example, when working with a team, developers might use CSS classes just for providing dynamic functionality with jQuery. Designers might note that these classes are not used for styling purposes and hence will have the possibility of removing them without knowing the importance.
So it’s good practice to use some prefix for CSS classes, which are only used for various functionalities instead of styling purposes.
Scenario 3 – Selecting elements using multiple classes
There are applications and websites which depend heavily on JavaScript and provide highly dynamic client side functionalities. In such scenarios, we may use a large number of classes and IDs for filtering, selection and applying the features.
Assume that we have a list of user records which needs to be filtered on the client side based on the role. We can define the roles as CSS classes to simplify the filtering process. Consider the following code snippet for this scenario.
<ul>
<li class=’role-developer role-designer’ >Mark</li>
<li class=’role-developer ’ >Simon</li>
<li class=’role-developer role-manager’ >Kevin</li>
</ul>
Let’s assume we want to get users who have both developer and designer roles. In such cases, we can use multiple CSS classes as shown in the following code.
var selected_users = $('.role-developer.role-designer');
We can use any number of classes, one after the other to match multiple classes on same element. Make sure not to use spaces between classes as it changes the meaning and result of the selection. Consider the same code line with spaces.
var selected_users = $('.role-developer .role-designer');
Now the code will look for designers who have a parent element called developer. So get used to the difference between the two implementations and use it wisely. Similarly, we can mix IDs and classes while using this technique.
Scenario 4 – Selecting elements using data attributes
HTML5 introduced custom data attributes where we can define data related to HTML elements. These data attributes have a certain set of conventions and are considered to be private data. So now we can store the data related to any element using data attributes instead of making several AJAX requests to the server. Let’s see how we can implement Scenario 2, with custom data attributes instead of CSS classes.
$( "input[data-type=’user_data’]" ).click(function(){
$(this).parent().parent().remove();
});
As you can see, we can achieve the same result with data attributes, instead of CSS classes.
jQuery provides advanced attribute selectors to support custom data attributes. So let’s consider some of the advanced selector options on custom attributes.
Assume that we have user email stored as custom attributes and we want to select users based on certain conditions in email. Consider the following code snippet with the use of data attributes.
<ul>
<li data-email=’mark@gmail.com’ data-type=’userdata’ >Mark</li>
<li data-email=’kevin@yahoo.com’ data-type=’userdata’ >Kevin</li>
<li data-email=’peter@gmail.uk’ data-type=’userdata’ >Peter</li>
</ul>
Selecting elements which have ‘gmail’ in their email
$( "input[data-email *=’gmail’]" );
Selecting elements with a ‘uk’ email addresses
$( "input[data-email $=’.uk’]" );
Selecting elements with invalid emails without the ‘@’ sign
$( "input[data-email !=’@’]" );
As you can see data attributes are powerful in working with data related to HTML elements and jQuery provides comprehensive support with its built-in functions. You can find the complete attribute selector reference at http://api.jquery.com/category/selectors/attribute-selectors/.
Scenario 5 – Selecting elements using multiple data attributes
This is similar to what we discussed in Scenario 3 with some extended features. Using CSS classes to cater for multiple data values can be complicated in advanced scenarios. So let’s see how we can use multiple data attributes for selection.
$( "input[data-type=’userdata’][data-email !=’@’]" );
Here, we can check the existence of multiple data attributes as well as selection through partial searching of values. Now you should be able to understand the difference between CSS classes and data attributes for element selection. Data attributes provide an organized way of handling element data.
The techniques discussed here can be used in combination with other jQuery filters to cater any type of advanced situation and it’s important to use them wisely.
Wrap Up
This article was intended for beginners to understand the basics of element ID, classes and custom data attributes. We discussed each of them with practical scenarios with the help of jQuery built-in functions. While doing so, we also identified some novice developer mistakes. Let’s recap the points discussed in this article to build a useful guideline for DOM selection.
- Use ID as much as possible for element selection as it provides a unique identifier within the document.
- Use classes or data-attributes in multiple element scenarios, instead of relying on element ID.
- Make sure to differentiate your styling classes from the classes used for selection and functional purposes.
- Use data attributes for complex scenarios as classes are not intended to provide data about elements.
Hope you had a good beginning to element selection through this article. If you have better guidelines and element selections techniques, feel free to share them in the comments section.