agyanadda@gmail.com

jQuery Syntax

jQuery Basics 1 min read Updated Dec 1, 2026 Topic 3 of 25

Almost every jQuery line follows one pattern:

$(selector).action();
  • $ — calls jQuery
  • (selector) — finds HTML elements, using CSS selector syntax
  • .action() — does something to them

Examples

  • $('p').hide() — hide all paragraphs
  • $('#menu').show() — show the element with id menu
  • $('.price').css('color', 'green') — make all .price elements green

Works on many elements at once

$('li').addClass('done') changes every li — no loop needed.

Getters and setters

The same method reads or writes:

  • $('#name').text() — get the text
  • $('#name').text('Asha') — set the text

jQuery object

$('p') returns a jQuery object (a list of matched elements). $('p').length tells you how many were found.

Example

Example — One action, many elements HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>
<p id="info"></p>
<button id="go">Style all items</button>

<script>
  $(function () {
    $('#info').text('Found ' + $('li').length + ' list items.');
    $('#go').click(function () {
      $('li').css({ color: 'white', background: '#1f386b', padding: '4px', margin: '2px' });
      $('#info').text('Changed: ' + $('li').first().text() + ' and the others');
    });
  });
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does $('p').hide() do?

Exercise 2 True / False

$('#name').text() without an argument reads the text.

Exercise 3 Fill in the Blank

$('li').___ gives the number of matched elements.

Frequently Asked Questions

if ($('#banner').length) { ... } — length is 0 when nothing is found.