What are jQuery selectors and how to cache jQuery selectors to improve performance of your web page

Every time you use a selector the elements in Document Object Model (DOM) are searched to match your query or selector. Doing this kind of works too often or repeatedly will decrease the performance of your web page. If you refer to a specific selector too often or repeatedly you should consider to add it to a cache by assigning to a variable.

Before diving into the actual example I am going to first tell you, what are elements and what are selectors?

Elements are basically HTML tags such as div, p, a etc. These are called DOM elements. div is division element, p denotes paragraph element, a denotes anchor element.

A selector or jQuery selector selects or finds DOM elements in HTML document. Selectors are used to find elements based on id, class, name, types, attributes, etc. The function returns either an element or a list of elements. Here I will show you how to select DOM elements based on various selector types.

Generally you don’t want to select all elements from the DOM but you want to select those elements which are required to perform certain actions.

You can select all elements using $("*"). You can select all div elements using $("div") or all paragraph elements using $("p"). You can select all elements (div, p, span, etc.) having class green using $(".green").

You can select all elements (div, p, span, etc.) having class green and red using $(".green.red"). You can select all elements (div, p, span, etc.) having class green or red using $(".green, .red").

You can select any element (div, p, span, etc.) having id searchform using $("#searchform"). If you want to select all elements having attribute href then use $("[href]"). If you want to select an element having attribute href with value roytuts.com then use $("[href='roytuts.com']").

Now I am going to give you some examples on relational operators, where you may have to select child elements instead of the parent elements.

Let’s say you want to select all <span>s that are descendants of a div or paragraph. Then you can use the jQuery selector as $("div span") or $("p span"). If you want to select all <span>s that are direct children of a paragraph then you can use $("p > span"). You can use $("p ~ span") to select all siblings following a <p>. You can use $("a + span") to select all <span>s immediately after <a>.

The following subsequent sections shows how to select elements using jQuery selector. Take the following HTML examples:

<a href="https://wwww.roytuts.com"></a> <!-- 1 -->
<div id="div-link"></div> <!-- 2 -->
<p class="example"></p> <!-- 3 -->
<span class="example"></span> <!-- 4 -->
<a class="example" href="https://wwww.roytuts.com"></a> <!-- 5 -->
<a href="https://wwww.roytuts.com"></a> <!-- 6 -->

You can select elements by type. The following jQuery selector will select all anchor (<a>) elements, including 1, 5 and 6.

$("a")

You can select elements by class. The following jQuery selector will select all elements of class example, which are 3, 4 and 5.

$(".example")

You can select element by id. The following jQuery selector will select the element with the given id, which is 2.

$("#div-link")

You can selecting by an attribute. The following jQuery selector will select all elements with a defined href attribute, including 1, 5 and 6.

$("[href]")

You can also select element by attribute value. The following jQuery selector will select all elements where the href attribute exists with a value of index.html, which are 1, 5 and 6.

$("[href='https://wwww.roytuts.com']")

You can also select elements by index position. The following jQuery selector will select only 1, the fifth one, because index supplied is 1 like
eq(4). Note that the index starts at 0 hence the fifth one got selected here.

$("a:eq(4)")

You can select element with index exclusion. To exclude an element by using its index, use for example to exclude the first element, not(:eq(0)).

$("a").not(":eq(0)")

You can also select elements with exclusion by class name. To exclude an element from a selection, use :not(). The following selects elements, except those with the class example, which are 1 and 6.

$("a:not(.example)")

You can select elements by pseudo-state. You can select using pseudo-states, including :first-child, :last-child, :first-of-type, :lastof-
type
, etc. The following jQuery selector will only select the first element, i.e., 1.

$("a:first-of-type")

You can combine multiple jQuery selectors to select multiple elements. You can combine any number of jQuery selectors or combine all of them. You can also select multiple classes, attributes and states at the same time. For example,

$("p.class1.class2.class3#divId[attr1][attr2='attributename'][attr3='anotherattributename']:first-of-type:firstchild")

The above jQuery selectors would select an element that:

  • Has the classes: class1, class2, and class3
  • Has the id: divId
  • Has the attribute: attr1
  • Has the attributes and values: attr2 with value attributename, attr3 with value anotherattributename
  • Has the states: first-child and first-of-type

You can also separate various selectors with comma as shown below:

$("p, .class1, #idvalue")

The above example would select:

  • All elements
  • All elements that have the class class1
  • An element with the id #idvalue

You can use wildcard selection by which you want to select all elements but there is no common property to select upon (class, attribute etc). In such situation you can use the * selector that simply selects all the elements, for example, you want to select all elements inside #divwrapper element:

$('#divwrapper *')

Enough talking about jQuery selectors in the above sections. Now let’s dive into how you can cache the jQuery selectors to improve the performance of your web page.

As repeatedly calling the jQuery can decrease your page’s performance. Therefore it is a wise decision to add it to the cache by assigning it to a variable when you refer a specific selector again and again. For example, you are referring repeatedly to the element having an id value msg, so assign it to a variable.

var msg = $('#msg');
msg.show();

The above would be replaced as:

$('#msg').show();

Caching the above selector would prove helpful if your website needs to show/hide this element often.

If there are multiple elements with the same selector, the variable will become an array of these elements. For example, look at the below HTML and jQuery part:

<div class="wrapper">
   <div class="child-div">Child Div 1</div>
   <div class="child-div">Child Div 2</div>
</div>
<script>
   var children = $('.child-div');
   var firstChildText = children[0].text();
   console.log(firstChildText);
   // output: "Child Div 1"
</script>

The element has to exist in the DOM at the time of its assignment to a variable. If there is no such element in the DOM with a class then you will get an empty array in that variable.

Let’s take a look at the following example:

<div class="wrapper"></div>
<script>
   var parent = $('.wrapper');
   var children = $('.child-div');
   console.log(children);
   // output: []
   parent.append('<div class="child-div">Child Div 1</div>');
   children = $('.child-div');
   console.log(children[0].text());
   // output: "Child Div 1"
</script>

Remember you need to reassign the selector to the variable after adding/removing elements in the DOM with that selector.

Let’s take a look at the following how to reassign the selector to the variable.

var msg = $('#msg');
msg.show();

That’s all about jQuery selectors and how to cache jQuery selectors to improve page’s performance.

Leave a Reply

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