jQuery Selectors

jQuery is a JavaScript library and this write less and get more system.It makes thing like HTML and css document traversal and you can do event handling and animation using jquery.

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

Before Starting the article you need to consider few things, use jQuery CDN in head tag in the
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

You can write the jQuery code in head as well as in body with the<script></script> tag

So here you are going to see three jQuery Selectors:

The Element Selector
The #id Selector
The .class Selector

So, here we go!

The Element Selector


The jQuery selector selects elements based on the element name.

You can select all <p> elements using this syntax:

$("p")

Example


When user clicks on the Hide button all <p> elements will be hidden

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide(1000);
  });
});
</script>
</head>
<body>

  <button>Hide</button>
  <p>This is first paragraph.</p>
  <p>This is another paragraph.</p>

</body>
</html>

The #id Selector


The id selector should be unique on your current page. Using id of that element you can edit the html code using jquery.

Syntax:

$("#hide")

Example


When a user clicks on the Hide button, the element with id name "hide" will be hidden

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#hide").hide(1000);
  });
});
</script>
</head>
<body>

  <button>Hide</button>
  <p>This is first paragraph.</p>
  <p id="hide">This is another paragraph.</p>

</body>
</html>


The .class Selector


The .class selector selects the elements based on their specified class name.

Syntax:

$(".hide")

Example


When a user clicks on the Hide button, the elements with class name "hide" will be hidden

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $(".hide").hide(1000);
  });
});
</script>
</head>
<body>

  <h2>This is a heading</h2>
  <button>Hide</button>
  <p>This is a paragraph.</p>
  <p class="hide">This is another paragraph.</p>

</body>
</html>


Did you like our works?

We are known for Website Development and Website Designing, along with Android iOS application development in Mumbai, India. Please write us what you think, we would like to hear it from you

1