Jquery Selectors

jQuery selectors will help to select and manipulate HTML element(s).

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

Mainly three type of selectors.

  • element Selector
  • #id Selector
  • .class Selector

Lets check each.

1)element Selector

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

You can select all <span> elements on a HTML page like this:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("span").hide();
  });
});
</script>
</head>
<body>
<span>This is another paragraph.</span>
<button>Click Here</button>
</body>
</html>

2) #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, #id selector when you want to find a single, unique element.

To find an element with a specific id you can write $("#divid")

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#divid").hide();
  });
});
</script>
</head>
<body>
<div>Div-1</div>
<div id="divid">Div-2</div>
<button>Click me</button>
</body>
</html>

3).class Selector

The jQuery .class selector finds elements with a specific class.

One page can have multiple classes with same name.

To find an specific class you can write $(".divid")

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $(".divid").hide();
  });
});
</script>
</head>
<body>
<div>Div-1</div>
<div class="divid">Div-2</div>
<button>Click me</button>
</body>
</html>

 

There are others important selectors.

1)Want to select all elements you can write $("*")

2)Want to select the current HTML element you can write $(this)

3)Want to select all elements with an href attribute you can write $("[href]")

4)Want to select the first <span> element you can write $("span:first")

 

Leave a reply

your email address will not be published. required fields are marked *

Name *
Email *
Website