Advanced Selectors used in jQuery
 
 

  There are numerous selectors that you can use both in CSS and in jQuery. With jQuery, you can use advanced selectors that help you reference various elements in an HTML page and then apply properties and call methods as needed. In this article, we'll show you how to use more advanced selectors to format and manipulate HTML elements using jQuery. 

Why Use Advanced Selectors?

In some more advanced web applications, you need more control than just referencing several element types or one with a specific ID. You can have several classes and subclasses and referencing one of them might not be enough to properly work with your elements. 

Remember that a web page can contain hundreds of elements, so you might not even know the elements' names. For instance, you could have a page with a list of orders for a customer. If the customer has a hundred orders, you could have a hundred elements on the page. The IDs and names on the page could be created dynamically. 

To compensate for this complexity, jQuery and CSS have advanced selectors that let you choose elements based on location in the page or by descendants or even by adjacent siblings. You wouldn't know the IDs, classes or names of these elements, but you're still able to query them based on HTML location. In the example of a list of orders for a customer, this would benefit you when you don't know the IDs for each order element. Instead, you can reference them based on the container that holds them or their location to another element. 

Efficiency with Selectors

You shouldn't use just any selector with your jQuery code. Not every selector is efficient, and performance and efficiency should be a priority when you design and write your code. 

 What if you have hundreds of elements? This makes for inefficient code, and you want to avoid inefficient code. The more elements you query and reference, the less efficient your code becomes. 

The most efficient selectors are ones that retrieve one element. This means the ID selector is the most efficient. Class and HTML type selectors are the next most efficient. Next are adjacent siblings, child elements, and descendants. Attribute and pseudo-class selectors are the least efficient. 

Even with inefficient selectors, you still need to use them occasionally. Just keep in mind that if you can use a better, more efficient way to reference elements, always choose an alternative for performance reasons. 

Traversing and Filter Selectors

Filter selectors are considered advanced selectors that let you traverse HTML elements based on proximity or location. There are numerous filter selectors, but you will run into a few more often than others. 

A filter selector is basically one that grabs a group of elements based on the method that you use. 

Let's first take a look at the filter() method in jQuery. 

<ul>

 <li>Red</li>

 <li>Blue</li>

 <li>Green</li>

</ul>

Suppose that we wanted to create an unordered list that had an alternating background color to make it easier for the reader to read through items. Just like our list of orders example, you could have one or a thousand items in your unordered list. For that reason, you need to query the list using filters and then using the reference to set the background color on alternating items. 

The following code uses the filter object to set a background color on alternating odd-numbered items.

$( "li" ).filter( ":odd" ).css( "background-color", "blue" );

Notice that the first function parameter is the "li" element type. This tells the JavaScript engine to get list items on the page. In this example, we only have one unordered list. Notice that the ul HTML tag isn't specified or you would get the ul object and not the list items. 

We then use the "filter" method. In this method is the filter you want to use. We use the "odd" filter. In this example, only the Blue item has the blue background. You might wonder why Blue has the blue background, when Blue is #2 in the list. This should make it an even number. However, just like any other language, jQuery index numbers start with 0. This means that Red gets the index 0, Blue gets the index of 1, and Green has an index of 2. Therefore, Blue is the only odd item in your list. 

The above code is just one example of how you can use jQuery to format and style items in a page. It's beneficial when you don't know the number of elements that are printed from dynamic backend code. 

We can also use jQuery filter selectors to work with elements in proximity to other elements. For instance, you might want to change the border of several containers within other containers in a list. You can also use jQuery to perform this task. 

First, we need some div containers in our HTML page. The following HTML code is a list of div containers, which are commonly used for this type of styling.

<div></div>

<div class="main"></div>

<div class=" main "></div>

<div class=" main "></div>

<div class=" main "></div>

<div></div>

You should notice from the above HTML that you have an opening blank container and then four "middle" containers named "main." Then, you have a final blank container. The "main" div elements are in the "middle" of the two blank ones. We can use this proximity information to format them based on jQuery. 

Take a look at the following jQuery code.

<script>

$( "div" )

 .filter( ".main" )

    .css( "border-color", "blue" );

</script>

In this code, we use the "div" HTML element. We only have 6 div elements in our HTML code, but remember that this selector grabs all div elements on the page. The "filter" method is then used, and it has the ".main" class specified. Remember that a name preceded by a period indicates that you want to select an element with a class name. 

The filter method in this example gets all of the "main" div containers, and then the css method sets the border color. This is also a good example of chaining methods in jQuery. 

You can also add and delete elements from a list of HTML tags. Let's take a look at the add method. When you use the add method and want to reference it, you must use it at the same time you assign it to a variable. The following code shows you how to work with the add method.

var addeddiv = $( "p" ).add( "div" );

In the code above, the selector gets a "p" (paragraph) element and adds a div to it. The added div is then assigned to the JavaScript variable "addeddiv." This is an important syntax rule. The following code won't reference the new div.

var addeddiv = $( "p" );

addeddiv.add( "div" );

In the above code, the addeddiv variable is first assigned to the paragraph selector. After the variable is assigned, then the add method is invoked. In the above code, the you won't have the expected results. You must use the add method at the same time you assign the variable. 

As you might already know, HTML is made up of elements contained within elements. The top-level element is called the parent. The elements contained within parent elements are called children. The children elements can have their own children, and these children can have even more children. 

Because it's difficult to drill down to specific elements within a page, you can instead use the "children" method in jQuery. This method lets you then manipulate values within child elements or set their CSS classes. 

Take a look at the following HTML elements.

<p>This is <span>a child container</span> within a parent paragraph element</p>

In the code above, the paragraph element (p) contains the span element. This makes the paragraph element the parent and the span element is the child. You can use the children method to grab the span object and set its style or text. Take a look at the following jQuery code.

<script>

$( "p" ).children().css( "border-bottom", "3px double red" );

</script>

In the above code, the p tag is used as the selector, and then the children method is called. The children method then gets any HTML elements contained in the parent. In this example, we only have one children node, so the text "a child container" has a red double underline under its text. The text outside of the span element is not changed, because it's not contained in any child nodes. 

You can traverse through several elements using the "each" method. For anyone who knows another programming language, you are probably familiar with the "foreach" loop that's common in most C-style languages. The "each" method in jQuery is similar to this loop structure. 

Suppose we want to traverse through several list items in an unordered list. We can use the same list we used in the previous sections.

<ul>

 <li>Red</li>

 <li>Blue</li>

 <li>Green</li>

</ul>

Let's say you want to debug your list items and print the text located in each li element. The console.log command writes debug information to the console. It's used to review output without using the common JavaScript alert function. It's cleaner and doesn't leave any bugs in your application. Take a look at the following code.

$( "li" ).each(function( index ) {

 console.log( "The text in element number" + index + ": " + $( this ).text() );

});

The first selector gets each HTML li element. Then, the "each" method has its own function that grabs the number of elements and loops through them. The index variable contains each index number as a new iteration is started. Remember that jQuery arrays and objects start with an index of 0, so the starting index value is 0 and the final element has the index of 2. 

This loop will iterate three times, and each iteration writes the text "The text in element number " with the index number is written to the console. Then, the text contained within the li element is written to the console. 

The "eq" method lets you specify an element index that you want to change in your arrays. We can again use the unordered list from the previous section. Again, the list is shown below.

<ul>

 <li>Red</li>

 <li>Blue</li>

 <li>Green</li>

</ul>

Suppose you want to change the first element to a red background. The following jQuery code changes the Red list item to a red background.

$( "li" ).eq( 0 ).css( "background-color", "red" );

Again, the first selector specifies that you want li elements. The second eq method tells the JavaScript engine which index value to reference. Remember that index values start with zero, so specifying 0 as the eq method parameter references the first item. 

You can also use negative numbers in the method's parameter list. Look at the following code.

$( "li" ).eq( -2 ).css( "background-color", "red" );

In the above example, the indexing starts at the bottom of the list and traverses upwards. Therefore, Green is the first list item, Blue is the second, and Red is the third. The -2 value points to the Red item again. 

The final selector we'll cover is the "siblings" selector. We showed you how to get child nodes, but you can also select all of the element's siblings. Again, we'll take the unordered list of colors we keep using.

<ul>

 <li>Red</li>

 <li class="blue">Blue</li>

 <li>Green</li>

</ul>

We added a class in the second element, so we can distinguish it from the rest. Now, let's apply jQuery formatting to the code.

$( "li.blue" ).siblings().css( "background-color", "white" );

In the above jQuery code, the engine finds the list element with the class named "blue." All siblings of this element are then set to a white background. Note that the Blue item does not have any background changes applied. Only the element siblings are affected. This means that Red and Green now have a white background. 

Creating Your Own Selector

JQuery has numerous selectors. You won't normally need to create your own. In rare cases, though, you might want to create your own to make it easier to reference a section of your page. 

Customized jQuery selectors work similarly to the standard ones. You set up a function that defines the name of the selector and the filter that's applied to find the ones that you want. Take the following jQuery function for example.

$.expr[':'].withName = function(obj){

 var $this = $(obj);

 return ($this.attr('name') != '');

};

In the above code, we specify that we're creating a custom jQuery selector using the $.expr statement. Then, the next name after the colon brackets indicates the custom selector name. In this example, the custom selector is given the name "withName."

After the selector name definition, you create a function that tells jQuery what elements to select. In the "return" statement, you see the filter. The filter states that you only want to retrieve elements where the name attribute is not blank. This filter will grab all HTML elements that have a name attribute defined. 

That's all it takes to build your own selector. You can reference the selector and its elements using the following code.

$('a: withName').css('background-color', 'white');

In the code above, all elements that match the custom selector are given a white background.

Selectors will be a part of any jQuery code you write. It's how JavaScript can identify one element from another. Just remember that your use of selectors should be optimized for performance and efficiency for your pages.