jQuery Syntax
The jQuery syntax is essential for leveraging its full potential in your web projects. It is used to select elements in HTML and perform actions on those elements.
jQuery Syntax
$(selector).action()
Where -
- $ - It the the shorthand for jQuery function.
- (selector) - It defines the HTML element that you want to select
- action() - It is the jQuery method used to perform actions on the elements.
Syntax of jQuery Selectors
Selectors in jQuery are used to target specific elements in the HTML document. They are similar to CSS selectors and can be used to select elements by tag name, class, ID, or attributes.
- Element Selector: Selects all elements of a specified type.
$('p') // Selects all <p> elements
- Class Selector: Selects all elements with a specific class.
$('.className') // Selects all elements with class 'className'
- ID Selector: Selects an element with a specific ID.
$('#Id') // Selects the element with ID 'Id'
- Attribute Selector: Selects elements with a specific attribute.
$('input[type="text"]') // Selects all <input> elements with type 'text'
Syntax of jQuery Methods
jQuery provides a wide range of methods for manipulating HTML elements, handling events, and performing animations.
1. Manipulating HTML/Text Content
.html(): Sets the HTML content of selected elements.
// Sets HTML Content
$('#element').html('New Content');
.text(): Sets the text content of selected elements.
// Sets the Text Content
$('#element').text('New Text');
2. Changing CSS Styles with jQuery
.css(): Sets the CSS properties of selected elements.
// Sets the Text Color to Red
$('#element').css('color', 'red');
// Sets Multiple CSS Styles
$('#element').css({
"color": "red",
"backgroundColor": "green"
});
3. Event Handling with jQuery
.click(): Attaches a click event handler to the selected elements.
$('#button').click(function() {
alert('Button Clicked!');
});
4. Show/Hide HTML Elements with jQuery
.show(): Displays the hidden elements.
$('#element').show();
.hide(): Hides elements.
$('#element').hide();
Syntax of Method Chaining in jQuery
One of the most powerful features of jQuery is method chaining. After selecting elements with jQuery, you can chain multiple methods together to perform several actions in a single line of code.
$('#element').css('color', 'blue').slideUp(1000).slideDown(1000);
This code selects the element with ID #element, and changes its text color to blue, slides it up over 1 second, and then slides it down over 1 second.
Syntax for jQuery with NoConflict Mode
If you are using multiple JavaScript libraries that might conflict with jQuery, you can use jQuery noConflict mode to avoid this issues.
jQuery.noConflict();
jQuery(document).ready(function($) {
// jQuery code here using $ as the alias
});
In this mode, jQuery can be used as the alias instead of $ to avoid conflicts.