jQuery Syntax
In this page:
Basic Syntax
Every jQuery statement follows the same shape -- $(selector).action() -- wrap a selector in the dollar function, then chain the operation you want.
Example: Basic Syntax
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="demo">Text</p>
<button id="btn">Hide</button>
<script>
$("#btn").on("click", function() {
$("#demo").hide();
});
</script>
</body>
</html>
Select by ID
An ID is unique per page by HTML convention, so a hash-prefixed selector like $('#header') is the fastest and most precise way to grab exactly one element when you know its id attribute.
Example: Select by ID
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<h1 id="header">Title</h1>
<script>
$("#header").css("color", "purple");
</script>
</body>
</html>
Select by Class
Classes can be reused across many elements, so a dot-prefixed selector like $('.item') returns a jQuery object wrapping every element sharing that class, letting you act on a whole group at once.
Example: Select by Class
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p class="item">One</p>
<p class="item">Two</p>
<script>
$(".item").css("color", "green");
</script>
</body>
</html>
Change CSS
The .css() method reads or sets an individual CSS property directly through JavaScript, which is handy for quick style tweaks but is usually better replaced with toggling a class for anything more than a one-off change.
Example: Change CSS
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="box">Styled</p>
<script>
console.log($("#box").css("font-size"));
$("#box").css("font-size", "20px");
</script>
</body>
</html>
Hide and Show
The .hide() and .show() methods toggle an element's display style between none and its previous value, giving you a simple way to reveal or conceal content without writing any CSS yourself.
Example: Hide and Show
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="box">Toggle me</p>
<button id="btn">Toggle</button>
<script>
$("#btn").click(function() {
$("#box").hide();
$("#box").show();
});
</script>
</body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: