jQuery Basics

In this glitch sandbox we'll review the basic syntax of jQuery and some of the most common jQuery functions.

We'll walk through these functions together. Afterwards, try to re-create and experiment with these functions on your own by remixing this project.

When you use jQuery, make sure to wrap your code in the jQuery ready function $(document).ready().


Selecting Elements

The simplest thing we can do with jQuery is get some elements and do something with them. If you understand CSS selectors, getting some elements is very straightforward: you simply pass the appropriate selector to $().

$( '#header' ); // select the element with an ID of 'header'
$( 'li' );      // select all list items on the page
$( 'ul li' );   // select list items that are in unordered lists
$( '.person' ); // select all elements with a class of 'person'

.addClass()

Add class(es) to an element.


.toggleClass()

Toggle between class(es). Useful to toggle between active states, for example hiding and showing something when clicking a button.


.hasClass()

Check if an element has a class.


.hide()

Hide an element (set it to display: none).

This is the hide-demo text

.show()

Show an element (set it to display: block).


.toggle()

Toggle between hide() and show().

This is the toggle-demo text

.css()

Get or set CSS properties of an element.

This is the css-demo text

.html()

Get or set the HTML contents of the element.


.append()

Insert content to the end of the element.