### jQuery - Syntax

Almost everything we do with jQuery will start with a dollar sign ($). The basic syntax of jQuery is:

        $("selector").action();

#### Selecting elements

To select elements using jQuery we use selectors that are very similar to CSS selectors. In the below example, you can see how the selection is done by html tag, class or id:

        $(".example") // select all elements with the class of "example"
        $("p") // select all p elements
        $("#hamburger-icon") // select the element with the id of "hamburger-icon"

The actions mentioned above are jQuery methods. Let's start using these methods with a simple example. Let's hide all elements with the class of "example" when clicking the element with the id of "hide".

1
2
3
hide

        $( "#hide" ).click(function() {
            $(".example").css("display", "none");
        });

In this example we can see how jQuery simplifies things. But it's possible to simplify it even more, since jQuery comes with a built-in method that automatically apply display: none to elements:

        $( "#hide" ).click(function() {
            $(".example").hide();
        });

#### Other selectors for elements

Besides selecting elements by html tags, classes and id's, we also have a few other ways of selecting more specific elements:

Sintax | Description
--- | ---
$("*") | All elements
$("div.example") | All div elements with the class of "example"
$("p:first") | The first p element
$("ul li:first-child") | The first li element inside every ul element
$("[href]") | All elements that have an href attribute
$("a[target='_blank']") | All elements that have the target attribute set to "_blank"
$("a[target!='_blank']") | All elements that DON'T have the target attribute set to "_blank"
$(":button") | All elements that have the type attribute set to "button"
$("tr:even") | All even tr elements (0, 2, 4...)
$("tr:odd") | All odd tr elements (1, 3, 5...)

##### Note: Being a bit confused at this point is normal

In the beginning is normal to get a bit confused with jQuery because it has names and ways of executing things slightly different than in vanilla Javascript.

See two examples below:

        // jQuery's syntax
        element.click( function(){ } )

        // Javascript's syntax
        element.onclick = function(){ }

        // jQuery's syntax
        element.css("property", "value")

        // Javascript's syntax
        element.style.property = "value"

Don't worry too much about this now, in a short period of time jQuery's syntax will become natural to you. While it doesn't always remember that Google is there for us anytime we have any doubts. If you're unsure how to use the onclick event in jQuery just search for jquery onclick event and the answer you need will be in the first search result.

### Contents