What is jQuery
In this page:
Introduction to jQuery
jQuery wraps the raw browser DOM API in a friendlier, more consistent interface so you write less code to select and manipulate elements.
Example: Introduction to jQuery
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="msg">Hello</p>
<script>
document.getElementById("msg").style.color = "blue";
$("#msg").css("color", "blue");
</script>
</body>
</html>
Why Use jQuery
Before jQuery, developers had to write verbose, browser-specific code just to select an element or attach an event. jQuery collapsed that boilerplate into short, chainable one-liners, which is why it became the standard library for browser scripting for over a decade.
Example: Why Use jQuery
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="msg">Hello</p>
<script>
$("#msg").css("color", "red").text("Updated").fadeOut(1000).fadeIn(1000);
</script>
</body>
</html>
Selecting an Element
Selecting an element is the starting point for almost every jQuery snippet, since you can't change or read anything until you've grabbed a reference to it. The dollar-sign function, $(), accepts a CSS selector string and returns a jQuery object wrapping every match.
Example: Selecting an Element
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p class="greet">Hi</p>
<script>
var el = $(".greet");
console.log(el.length);
</script>
</body>
</html>
Changing Text
Once you have a jQuery object, .text() lets you read or overwrite the text content inside it without touching the surrounding HTML tags. This is one of the most common ways beginners update a page in response to user actions.
Example: Changing Text
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="msg">Old text</p>
<script>
console.log($("#msg").text());
$("#msg").text("New text");
</script>
</body>
</html>
Handling a Click
Click handling ties selection and behavior together: you select an element, then call .on(click, ...) or .click() to run a function whenever the user interacts with it. This pattern -- select, then react -- is the backbone of almost all interactive jQuery code.
Example: Handling a Click
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click me</button>
<script>
$("#btn").on("click", function() {
console.log("Button clicked");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: