jQuery is a open source library written JavaScript code. The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery selectors are used to find or select HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
The following table shows the basic illustration of CSS and jQuery Selectors
Element | CSS Selector | jQuery Selector | Description |
---|---|---|---|
HTML element | p | $('p') | Select all p element |
ID | #myId | $('#myId') | Select the element with id="myId" |
Class | .myClass | $('.myClass') | Select all elements with class="myClass" |
* | * | $('*') | Select all elements |
1. $("#myId")
The jQuery #myId selector uses the id attribute of an HTML tag to find the specific element.
$(document).ready(function(){
$("button").click(function(){
$("#myId").toggle();
});
});
Demo: https://jsfiddle.net/quanghoan/zz6q797a/$("button").click(function(){
$("#myId").toggle();
});
});
2. $("#myClass")
The jQuery class selector finds elements with a specific class.
Demo: https://jsfiddle.net/quanghoan/zz6q797a/1/
3. $(this)
Select current element: https://jsfiddle.net/quanghoan/zz6q797a/2/
$(document).ready(function(){
$("button").click(function(){
$(this).hide();
});
});
4. $("p.myClass")$("button").click(function(){
$(this).hide();
});
});
Selects all <p> elements with class="myClass".
$(document).ready(function(){
$("button").click(function(){
$("p.myClass").toggle();
});
});
Demo: https://jsfiddle.net/quanghoan/zz6q797a/3/$("button").click(function(){
$("p.myClass").toggle();
});
});
5. $(".myClass,#myId")
All elements with the class "myClass" or with the id "myId"
$(document).ready(function(){
$("button").click(function(){
$(".myClass,#myId").css("background-color","red");
});
});
Demo: https://jsfiddle.net/quanghoan/zz6q797a/4/$("button").click(function(){
$(".myClass,#myId").css("background-color","red");
});
});
6. $("div")
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
Demo: https://jsfiddle.net/quanghoan/zz6q797a/5/$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
0 Comments:
Post a Comment