Selectors in jQuery
The jQuery library allows using CSS and its own custom selectors for accessing and manipulating the HTML elements in DOM.
The library allows accessing the elements by:
- ID
- Class name
- Tag name
- Attribute
- Attribute Value
- Other selectors
ID Selector
ID selector refers to the id attribute of a tag for searching the corresponding element.As the id of each element is unique,the selector is useful only for finding a single tag at a time.
$(#)
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2> <p>This is a paragraph.</p> <p id="test">This is another paragraph.</p>
<button>Click ME</button>
</body>
</html>
CSS Selector
he 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:
$(.)
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script>
</head>
<body>
<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p >This is another paragraph.</p>
<button>Click ME</button>
</body>
</html>