jQuery Syntax
The basic syntax of jQuery is very simple. You select some HTML elements, and then you do an action on them.
$(selector).action()
- The dollar sign
$says that we use jQuery. It is a short name of the functionjQuery(). (selector)finds the HTML elements. It uses the same rules as CSS..action()is the work to do on the found elements.
Examples
<h2>Title</h2>
<p class="note">First</p>
<p class="note">Second</p>
<p id="last">Third</p>
$('h2').text('New title'); // change the text of all h2
$('.note').css('color', 'red'); // set a style for all elements with class note
$('#last').hide(); // hide the element with id last
<h2>New title</h2>
<p class="note" style="color: red;">First</p>
<p class="note" style="color: red;">Second</p>
<p id="last" style="display: none;">Third</p>
The selector can find many elements, and the action is applied to all of them. In the code above, both paragraphs with the class note got the red color.
$ and jQuery are the same
<p>Page</p>
console.log($ === jQuery);
true
If another library also uses the $ sign, you can use the long name jQuery. See jQuery noConflict.
Method chaining
Most jQuery methods return the jQuery object, so you can write many actions one after the other on the same elements:
<p id="box">Hello</p>
$('#box').text('Hello jQuery').css('color', 'blue').addClass('big');
<p id="box" style="color: blue;" class="big">Hello jQuery</p>
Semicolons and quotes
- End each statement with a semicolon.
- You can use single or double quotes in the selector. Use the same style in all your code.
Use a variable for a selection
If you use the same elements many times, save them in a variable. The name usually starts with $, as a habit.
<ul id="menu"><li>Home</li><li>About</li></ul>
var $items = $('#menu li');
console.log($items.length);
$items.addClass('menu-item');
2
<ul id="menu">
<li class="menu-item">Home</li>
<li class="menu-item">About</li>
</ul>
| Exercises & Assignments |
|---|
| No Content Found. |