Syntax:
It should start with $ followed by parenthesis.
For below html, you want to hide text on click of button.
So you need to select button with id “myButton” as $(“#myButton”) and div with id helloWorldDiv as $(“#helloWorldDiv”)
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<meta charset="UTF-8"> <title>jQuery</title> <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script> <script> $(document).ready(function() { $("#myButton").click(function() { $("#helloWorldDiv").hide() }); }); </script> <button id="myButton">Hide text</button> <div id="helloWorldDiv">Hello world</div> |
Live demo :
jQuery selector example
So here on button click , we have hidden helloWorldDiv text.
Example on various selectors :
Element selector:
If you just write element name with $(), it will select all those element of that type.
For example: if you use $(“div”) , it will select all the div element in DOM.
In this example, on click of button , we will change text of all div present in the DOM.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<meta charset="UTF-8"> <title>jQuery</title> <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script> <script> $(document).ready(function() { $("#myButton").click(function() { $("div").html("Hello java2blog") }); }); </script> <button id="myButton">Change all div text</button> <div id="helloWorldDiv">Hello John</div> <div id="helloWorldDiv">Hello Martin</div> <div id="helloWorldDiv">Hello Smith</div> |
Live demo:
jQuery element selector example
#Id selector :
For selecting element with id, you need to use $(#id).
Example:
So you need to select button with id “myButton” as $(“#myButton”) and div with id helloWorldDiv as $(“#helloWorldDiv”)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<meta charset="UTF-8"> <title>jQuery</title> <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script> <script> $(document).ready(function() { $("#myButton").click(function() { $("#helloWorldDiv").hide() }); }); </script> <button id="myButton">Hide text</button> <div id="helloWorldDiv">Hello world</div> |
Live demo :
jQuery id selector example
So here on button click , we have hidden helloWorldDiv text.
class selector:
You can get all elements which use some class of CSS.
You need to use $(.className) to select all elements which uses that class. Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<meta charset="UTF-8"> <title>jQuery</title> <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script> <script> $(document).ready(function() { $(".abc").css("background-color","orange"); }); </script> <div id="helloWorldDiv" class="abc">Hello John</div> <div id="helloWorldDiv">Hello Martin</div> <div id="helloWorldDiv" class="abc">Hello Smith</div> |
Live Demo:
jQuery class selector example
For more jQuery selectors, please refer jQuery selector API