JQuery Selectors

JQuery Selectors can be used to manipulate & access HTML elements. They can be used to access HTML elements based on tag name, id, class, types & attributes. Let's have a look at the apporaches using which we can select elements on a page.


Selecting Elements By Name


The Element selector selects an element based on the element name. For example, all the <h1> tags can be selected like this:



$("h1")


For example, the following code will select all the h1 tags in the document and change their background color:




$(document).ready(function(){
  //Change background of all h1 elements
  $("h1").css("background", "yellow");
});

Live Demo!


Selecting Elements By Attribute


The Attribute selector selects an element by one of its attributes, such as an input's type or a link's target, etc. For example, the below code will change the color of <input> elements with type text.


Example:


$(document).ready(function(){
  // Changing color of input element having type 'text'
  $('input[type="text"]').css("background", "yellow");
});

Live Demo!


Selecting Elements By Id


The ID Selector can be used to select a single element with unique ID in the web page.

For example, the following code will select and change the color of an element having the id attribute as id="test", when the document is ready:



$(document).ready(function(){
  // Change color of element with id 'test'
  $('#test').css("color", "green");
});

Live Demo!


Selecting Elements By Class Name


The Class selector can be used to select elements with a specfic class in a webpage.

For example, the following code will select and manipulate all the elements with the class attribute as class="first", when the document is ready:



$(document).ready(function(){
  // Change color of elements with class 'first'
  $('.first').css("color", "orange");
});

Live Demo!


Selecting Elements By Compound CSS Selector


We can combine the CSS selector to make the element selection even more precise. For example, we can combine an element selector with a class selector that has the specific type & class.



$(document).ready(function(){
  //selecting all h1 elements with class 'test'
  $("h1.test").css("color", "blue");
  // Selecting all li elements inside the ul element with id test
  $("ul#test li").css("color", "red");
});

Live Demo!