jQuery Selectors


You will have known about CSS selectors, as jQuery also has selectors by which is used to select and apply an HTML element.

jQuery selectors allow you to select and manipulate HTML elements.

With jQuery selectors, you can find elements based on their ID, classes, types, attributes, attribute values, and more. jQuery is based on existing CSS selectors, and also has some custom selectors of its own.

Element Selector

Element Selector is used to selecting any HTML element.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>
<body>
 <p>This is paragraph tag.</p>
  <button>Click here to hide p element</button>
</body>
</html>

Id selector

The jQuery #id selector uses the id attribute of an html tag to find the specific element. As id should be unique on a page, this selector allows to find a single unique element. to select some specific element with id '"demo" like as $("#demo");

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#demo").hide();
  });
});
</script>
</head>
<body>
 <p id="demo">This is paragraph tag.</p>
  <button>Click here to hide p#demo element</button>
</body>
</html>

Class selector

The jQuery .class selector uses the class attribute of an html tag to find the all elements with this class. As same class attribute value may be assigned to different elements, this selector allows selecting multiple elements. to select all elements with class '"demo" like as $(".demo");

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $(".demo").hide();
  });
});
</script>
</head>
<body>
  <h1 class="demo">This is heading tag.</h1>
 <p class="demo">This is paragraph tag.</p>
  <button>Click here to hide all .demo element</button>
</body>
</html>