Ways to select DOM element(s) - a guide to jQuery Selectors

Introduction:

I hope you are now familiar with the basics of jQuery. You can go through my earlier post in case you are new to jQuery, so that you are familiar with the basics and know about how it can be used and the different things we can achieve using jQuery. A very common task using jQuery is selecting DOM element to get/set value, change the element’s appearance, get/set different HTML attributes or may be associate an event with that element. Let’s look a closure look at different ways to select DOM elements.

jQuery Selector:

There are different ways to select DOM element(s) using jQuery. We can select element(s) using the Id, class, HTML attributes, attribute value and much more. Basically jQuery selector is based on the CSS Selectors (the way CSS selects DOM element) but it has some own custom selectors.

Let’s look at some selectors along with examples.

The ID selector:

It uses the Id attribute of the element. As we know that id of an element is unique within the page so #id selector is used when we want to select a single element. To select an element using #id selector we use the following syntax:


$("#myInput")



Refer the following example which uses the #id selector to set a value in a div


<html>

<head>
<scriptsrc="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>
<body>
<divid="TESTdIV"></div>
</body>
</html>
<scripttype="text/javascript">
functioninit(){
$("#TESTdIV").text("Hello world!");
    }
$(document).ready(init)
</script>


The Class selector:

It uses the class attribute of the element. When we use the .class selector all elements that have the mentioned class name as its css class will be selected. To select an element using .class selector we use the following syntax:


$(".myClass")


Refer the following example which uses the .Class selector to bind an event

<html>
<head>
<scriptsrc="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>
<body>
<buttonclass="btnClass">Button1</button>
<buttonclass="btnClass">Button2</button>
</body>
</html>
<scripttype="text/javascript">
functioninit(){
$(".btnClass").click(function(){
alert("Button Clicked");
        });
    }
$(document).ready(init)
</script>



The Element Selector:

It uses the HTML tag name of all the elements, by using this selector all the elements with the mentioned HTML tag will be selected. When we know we have to perform certain action for elements of a specific type, we can use this selector.

For Example:

  • $("div") – will select all divs in that HTML page 
  • $("input") – will select all Input elements in that HTML page
  

Attribute Selector:

With jQuery, you can actually find elements based on any kind of attribute. We may or may not consider the value of the attribute i.e. we can select elements where a particular attribute is present for the HTML element, at the same time we can look for a specific value of an attribute to select one or more elements. To use an attribute name we have to use the attribute name within the square brackets like [href] or [title].



We can even match the attribute value partially using ^= (to check ‘starts with’) or $= (to check ‘ends with’) or *= (to check ‘contains’).



For examples:

$("[title]") //Find all elements which have a title attribute.
$("input[name^='txt']")// Find all elements where a name attribute starts with ‘txt’
$("input[name$='myname']") // Find all elements where a name attribute ends with ‘myname’
$("input[name*='select']") // Find all elements where a name attribute contains ‘select’

The Relation Selector:

We can select elements based on their parent element. Whenselecting with parent element the child element can be a direct child of that parent element or it may be further down in the hierarchy.

The syntax are different depending on whether the child is the direct child or not. We have to use the ‘>’ syntax between the parent and child selector if we want to find an element which is the direct child.


For Example:
  • $("div > a") // Finds all elements with ‘a’ tag who are direct child of a ‘div’ 
  • $("div a") // Finds all elements with ‘a’ tag where that is present as a child element of a ‘div’ at any level
Refer the following example which uses the relation selector
<body>
<divid="divParent">
<b>Test text 1</b>
<i>Test text 2</i>
<divid="DivChild">
<b>Test text 3</b>
<i>Test text 4</i>
<div>
<b>Test text 5</b>
</div>
</div>
</div>
</body>
<scripttype="text/javascript">
$("#divParent > b").css("color", "red");   
</script>


In the above example we are looking for elements which is a direct child of an element with id ‘divParent’ and sets its colour as ‘red’. So only ‘Test text 1’will be rendered as red.

Now change the jQuery code as below
:


<scripttype="text/javascript">
$("#divParent b").css("color", "red");
</script>

Now ‘Test text 1’, ‘Test text3’ and ‘Test text 5’ will be rendered in ‘red’.


Combining different Selector:

As already gone through different jQuery selectors and there use, we can combine these selectors together and used to select one or multiple DOM elements. Also there are a few custom selectors which can be also be used.

Refer following examples:

  • $("p.row") //All <p> elements with class ‘row’.
  • $("p:first")//Selects the first <p> element of the page. 
  • $("ul li:first")//Selects the first <li> element of the first <ul>. 
  • $(":button")//Selects all <button> elements and <input> elements of type="button". 
  • $("tr:even")//Selects even tr elements. 
  • $("tr:odd")//selects odd tr elements.

Next:

Now as we know how to select the desired set of DOM element(s) in jQuery, we can now use these selectors and manipulate DOM as per our need. Look for my next post for DOM manipulation.

Comments

  1. Excellent thread Mrinmoy.. Its really helpful. We can also add few jQuery's inbuilt api like .filter(), .find() to enhance the selection of HTML elements...
    E.g. http://api.jquery.com/filter/
    Once again, great atricle...

    ReplyDelete

Post a Comment

Popular posts from this blog

Handling Events in jQuery – Few Advanced Notes and Faqs

Let's traverse through DOM Tree - Few advanced notes on jQuery Selectors