Unit 2 - JQuery
Unit 2 - JQuery
<script>
$(document).ready(function() {
$("button").click(function() {
$("p").hide();
});
});
</script>
</body>
</html>
Output
The #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, so you should use the #id
selector when you want to find a single, unique element.
• To find an element with a specific id, write a hash character,
followed by the id of the HTML element:
• $("#test")
• Example
• When a user clicks on a button, the element with id="test" will be
hidden:
• $(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
HTML and jQuery code to hide the element
with the ID "test" when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<title>Hide Element on Button Click</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button>Click to Hide</button>
<div id="test">This is the element with ID "test"</div>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#test").hide();
});
});
</script>
</body>
</html>
Output
jQuery css() Method- Changing
Style
•jQuery css() Method
• The css() method sets or returns one or more style
properties for the selected elements.
• Return a CSS Property
• To return the value of a specified CSS property, use the
following syntax:
• css("propertyname");
• Set a CSS Property
• To set a specified CSS property, use the following
syntax:
• css("propertyname","value");
Changing Style- Return a CSS
Property Example
<!DOCTYPE html>
<html>
<head>
<title>Get Background Color</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p style="background-color: #ff0000;">This is a paragraph.</p>
<button>Get Background Color</button>
<script>
$(document).ready(function() {
$("button").click(function() {
var backgroundColor = $("p").css("background-color");
alert("Background color: " + backgroundColor);
});
Output
Changing Style-
Set a CSS Property Example
<html><head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<p style="background-color:#ff0000">This is a paragraph.</p>
<button>Set background-color of p</button>
</body></html>
Changing Style-
Set a CSS Property Example
o/p
Output of Previous Code
<script>
$(document).ready(function() { After Clicking on button
$("button").click(function() {
$("p").remove();
});
});
</script>
</body>
</html>
References
• https://www.w3schools.com/jquery/jquery_get_started.a sp
• https://www.w3schools.com/jquery/jquery_css.asp
• https://www.w3schools.com/jquery/jquery_dom_add.asp