jQuery is a JavaScript library designed to simplify the client-side scripting of HTML. The syntax of jQuery is based on CSS selectors and it provides a powerful set of methods and functions for manipulating HTML elements and handling events.
Here are some basic jQuery syntax examples:
- Selecting elements: To select an HTML element using jQuery, you can use the following syntax:
$(selector)
For example, to select all paragraphs on a page, you can use the following code:
$("p")
- Chaining: You can chain multiple jQuery methods together, which allows you to perform several actions on the same element without having to select it again. Here’s an example:
$("p").addClass("my-class").fadeOut("slow");
This code selects all paragraphs, adds a class called “my-class” to them, and then fades them out slowly.
- Event handling: You can use jQuery to handle events, such as clicking on a button. Here’s an example:
$("button").click(function(){
alert("Button clicked!");
});
This code selects all buttons on a page and adds a click event listener to them. When the button is clicked, an alert box is displayed.
- Manipulating elements: jQuery provides a powerful set of methods for manipulating HTML elements. Here are some examples:
$("p").text("Hello world!"); // sets the text of all paragraphs to "Hello world!"
$("img").attr("src", "new-image.jpg"); // sets the src attribute of all images to "new-image.jpg"
$("div").addClass("my-class"); // adds a class called "my-class" to all divs
These are just a few examples of the many things you can do with jQuery. To learn more, check out the jQuery documentation at https://api.jquery.com/.