Web Technology - Old Questions

10. Discuss different types of jQuery Selectors with examples.

5 marks | Asked in Model Question

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. 

All selectors in jQuery start with the dollar sign and parentheses: $().

The different types of jQuery selectors are:

1. The element Selector

The jQuery element selector selects elements based on the element name.

E.g. When a user clicks on a button, all <p> elements will be hidden:

$(document).ready(function(){

  $("button").click(function(){

    $("p").hide();

  });

});

2. The #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. To find an element with a specific id, write a hash character, followed by the id of the HTML element:

E.g. When a user clicks on a button, the element with id="test" will be hidden:

$(document).ready(function(){

  $("button").click(function(){

    $("#test").hide();

  });

});

3. The .class Selector

The jQuery .class selector finds elements with a specific class. To find elements with a specific class, write a period character, followed by the name of the class.

E.g. When a user clicks on a button, the elements with class="test" will be hidden:

$(document).ready(function(){

  $("button").click(function(){

    $(".test").hide();

  });

});