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 function jQuery().
  • (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
HTML after the code runs

<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);
Console output

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');
HTML after the code runs

<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');
Console output

2

HTML after the code runs

<ul id="menu">
<li class="menu-item">Home</li>
<li class="menu-item">About</li>
</ul>

Note: jQuery methods can be used on one or on many elements with the same code, and you do not need a loop. Next: Document Ready.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is jQuery?
What are the advantages of jQuery?
What is the difference between jQuery and JavaScript?
How do you add jQuery to a web page?
What is the document ready function in jQuery?
What is the difference between $(document).ready() and window.onload?
What is the $ sign in jQuery?