Beginners Guide to DOM Selection with jQuery

Share this article

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.

Key Takeaways

  • jQuery is a commonly used JavaScript library that offers advanced DOM selection and filtering features. It is essential for front end developers to have a deep understanding of DOM elements to avoid conflicts and optimize performance.
  • HTML element tags, IDs, classes, and data attributes are used to select elements within the DOM tree. IDs are unique identifiers, classes are used to style elements and also for filtering and selecting elements, and data attributes define private data for an element.
  • jQuery allows for the selection of unique elements, multiple elements using classes, elements using multiple classes, elements using data attributes, and elements using multiple data attributes. It’s crucial to prevent the duplication of elements with the same ID and to differentiate styling classes from those used for selection and functional purposes.

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.

Frequently Asked Questions (FAQs) about DOM Selection with jQuery

What is the Document Object Model (DOM) in jQuery?

The Document Object Model (DOM) in jQuery is a programming interface for HTML and XML documents. It represents the structure of a document and allows a way to manipulate the content and structure. With DOM, programmers can create, navigate, and modify elements and content in HTML and XML documents.

How does jQuery simplify DOM manipulation?

jQuery simplifies DOM manipulation by providing easy-to-use APIs for handling events, creating animations, and developing Ajax applications. jQuery also provides a simple syntax to navigate and manipulate the DOM. It abstracts many of the complexities of dealing with raw JavaScript and DOM APIs, making it easier for developers to work with HTML documents.

What are the different types of DOM selectors in jQuery?

There are several types of DOM selectors in jQuery, including element selectors, ID selectors, class selectors, attribute selectors, and pseudo-class selectors. Element selectors select elements based on their element name. ID selectors select elements based on their ID attribute. Class selectors select elements based on their class attribute. Attribute selectors select elements based on an attribute or attribute value. Pseudo-class selectors select elements based on a certain state.

How can I select an element by its ID in jQuery?

To select an element by its ID in jQuery, you use the hash symbol (#) followed by the ID of the element. For example, to select an element with the ID “myElement”, you would use $(“#myElement”).

How can I select elements by their class in jQuery?

To select elements by their class in jQuery, you use the dot symbol (.) followed by the class name. For example, to select elements with the class “myClass”, you would use $(“.myClass”).

What are attribute selectors in jQuery and how do they work?

Attribute selectors in jQuery select elements based on their attribute or attribute value. They are written using square brackets ([]). For example, to select all elements with a “data-example” attribute, you would use $(“[data-example]”).

How can I select multiple elements in jQuery?

You can select multiple elements in jQuery by separating each selector with a comma. For example, to select all elements with the class “myClass” and all elements with the ID “myID”, you would use $(“.myClass, #myID”).

What are pseudo-class selectors in jQuery?

Pseudo-class selectors in jQuery select elements based on a certain state. For example, the “:checked” pseudo-class selector selects all checked checkboxes or radio buttons.

How can I use jQuery to manipulate the DOM?

jQuery provides several methods for manipulating the DOM, such as .append(), .prepend(), .after(), .before(), .remove(), and .empty(). These methods allow you to insert, replace, and remove elements in the DOM.

How does jQuery handle events in the DOM?

jQuery provides methods for handling events in the DOM, such as .click(), .dblclick(), .hover(), .mousedown(), .mouseup(), .mousemove(), .mouseout(), .mouseover(), .mouseenter(), .mouseleave(), .change(), .focus(), .blur(), .keydown(), .keypress(), .keyup(), .submit(), .load(), .resize(), .scroll(), and .unload(). These methods allow you to define what happens when these events occur on elements in the DOM.

Rakhitha NimeshRakhitha Nimesh
View Author

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on Building Impressive Presentations with Impress.js. He is a regular contributor to 1stWebDesigner, Tuts+ network and SitePoint network. Make sure to follow him on Google+.

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