jQuery Syntax and Selectors

Basic jQuery Syntax

The basic syntax of jQuery is: $(selector).action(). It starts with the dollar sign $, followed by a selector, and then an action (also called a method).

Example:


<script>
  $(document).ready(function() {
    $("p").css("color", "blue");
  });
</script>

Output:

This paragraph will turn blue using jQuery.


$ and jQuery Function

$ is a shorthand for jQuery. Both can be used to access jQuery features. You can use either based on your preference.

Example:


<script>
  $(document).ready(function() {
    jQuery("h4").css("background", "#f0f0f0");
  });
</script>

Output:

This heading uses jQuery() instead of $()


Selecting Elements

You can select HTML elements using:

  • ID selector: $("#id")
  • Class selector: $(".class")
  • Tag selector: $("tag")

Example:


<div id="box">This is a box.</div>
<div class="highlight">Highlight me</div>
<p>This is a paragraph.</p>

<script>
  $(document).ready(function() {
    $("#box").css("border", "2px solid red");
    $(".highlight").css("background", "yellow");
    $("p").css("font-style", "italic");
  });
</script>

Output:

This is a box.
Highlight me

This is a paragraph.


jQuery Filters

jQuery filters are used to narrow down element selections. Common filters include:

  • :first - Selects the first matched element
  • :last - Selects the last matched element
  • :even - Selects elements with even index (0-based)
  • :odd - Selects elements with odd index

Example:


<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>

<script>
  $(document).ready(function() {
    $("li:first").css("color", "green");
    $("li:last").css("color", "red");
    $("li:even").css("font-weight", "bold");
  });
</script>

Output:

  • Item 1
  • Item 2
  • Item 3
  • Item 4

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!