Ad

Ad

Monday, 5 May 2014

jQuery Introduction

The purpose of jQuery is to make it much easier to use JavaScript on your website.

What You Should Already Know

Before you start studying jQuery, you should have a basic knowledge of:
  • HTML
  • CSS
  • JavaScript
If you want to study these subjects first, find the tutorials on our Home page.

What is jQuery?

jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains the following features:
  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities
Tip: In addition, jQuery has plugins for almost any task out there.

Why jQuery?

There are lots of other JavaScript frameworks out there, but jQuery seems to be the most popular, and also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
  • Google
  • Microsoft
  • IBM
  • Netflix
Note Will jQuery work in all browsers?

The jQuery team knows all about cross-browser issues, and they have written this knowledge into the jQuery library. jQuery will run exactly the same in all major browsers, including Internet Explorer 6!

jQuery Tutorial

"Try it yourself" Examples in Each Chapter

With our online editor, you can edit the code, and click on a button to view the result.

Example

$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
});

Try it yourself »
Click on the "Try it yourself" button to see how it works.

jQuery Examples

Learn by examples! At W3Schools you will find a lot of jQuery examples to edit and test yourself.


jQuery References

At W3Schools you will find a complete reference of all jQuery objects and methods.

jQuery Properties

jQuery Properties

Method Description
context Deprecated in version 1.10. Contains the original context passed to jQuery()
jquery Contains the jQuery version number
jQuery.fx.interval Change the animation firing rate in milliseconds
jQuery.fx.off Globally disable/enable all animations
jQuery.support A collection of properties representing different browser features or bugs (Intended for jQuery's internal use)
length Contains the number of elements in the jQuery object

jQuery Miscellaneous Methods

jQuery Misc Methods

Method Description
data() Attaches data to, or gets data from, selected elements
each() Execute a function for each matched element
get() Get the DOM elements matched by the selector
index() Search for a given element from among the matched elements
$.noConflict() Release jQuery's control of the $ variable
$.param() Create a serialized representation of an array or object (can be used as URL query string for AJAX requests)
removeData() Removes a previously-stored piece of data
size() Deprecated in version 1.8. Return the number of DOM elements matched by the jQuery selector
toArray() Retrieve all the DOM elements contained in the jQuery set, as an array

jQuery AJAX Methods

jQuery AJAX Methods

AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.
The following table lists all the jQuery AJAX methods:
Method Description
$.ajax() Performs an async AJAX request
$.ajaxPrefilter() Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()
$.ajaxSetup() Sets the default values for future AJAX requests
$.ajaxTransport() Creates an object that handles the actual transmission of Ajax data
$.get() Loads data from a server using an AJAX HTTP GET request
$.getJSON() Loads JSON-encoded data from a server using a HTTP GET request
$.getScript() Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request
$.param() Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
$.post() Loads data from a server using an AJAX HTTP POST request
ajaxComplete() Specifies a function to run when the AJAX request completes
ajaxError() Specifies a function to run when the AJAX request completes with an error
ajaxSend() Specifies a function to run before the AJAX request is sent
ajaxStart() Specifies a function to run when the first AJAX request begins
ajaxStop() Specifies a function to run when all AJAX requests have completed
ajaxSuccess() Specifies a function to run when an AJAX request completes successfully
load() Loads data from a server and puts the returned data into the selected element
serialize() Encodes a set of form elements as a string for submission
serializeArray() Encodes a set of form elements as an array of names and values

jQuery Traversing Methods

Query Traversing Methods

Method Description
add() Adds elements to the set of matched elements
addBack() Adds the previous set of elements to the current set
andSelf() Deprecated in version 1.8. An alias for addBack()
children() Returns all direct children of the selected element
closest() Returns the first ancestor of the selected element
contents() Returns all direct children of the selected element (including text and comment nodes)
each() Executes a function for each matched element
end() Ends the most recent filtering operation in the current chain, and return the set of matched elements to its previous state
eq() Returns an element with a specific index number of the selected elements
filter() Reduce the set of matched elements to those that match the selector or pass the function's test
find() Returns descendant elements of the selected element
first() Returns the first element of the selected elements
has() Returns all elements that have one or more elements inside of them
is() Checks the set of matched elements against a selector/element/jQuery object, and return true if at least one of these elements matches the given arguments
last() Returns the last element of the selected elements
map() Passes each element in the matched set through a function, producing a new jQuery object containing the return values
next() Returns the next sibling element of the selected element
nextAll() Returns all next sibling elements of the selected element
nextUntil() Returns all next sibling elements between two given arguments
not() Remove elements from the set of matched elements
offsetParent() Returns the first positioned parent element
parent() Returns the direct parent element of the selected element
parents() Returns all ancestor elements of the selected element
parentsUntil() Returns all ancestor elements between two given arguments
prev() Returns the previous sibling element of the selected element
prevAll() Returns all previous sibling elements of the selected element
prevUntil() Returns all previous sibling elements between two given arguments
siblings() Returns all sibling elements of the selected element
slice() Reduces the set of matched elements to a subset specified by a range of indices

jQuery HTML / CSS Methods

jQuery HTML / CSS Methods

The following table lists all the methods used to manipulate the HTML and CSS.
The methods below work for both HTML and XML documents. Exception: the html() method.
Method Description
addClass() Adds one or more class names to selected elements
after() Inserts content after selected elements
append() Inserts content at the end of selected elements
appendTo() Inserts HTML elements at the end of selected elements
attr() Sets or returns attributes/values of selected elements
before() Inserts content before selected elements
clone() Makes a copy of selected elements
css() Sets or returns one or more style properties for selected elements
detach() Removes selected elements (keeps data and events)
empty() Removes all child nodes and content from selected elements
hasClass() Checks if any of the selected elements have a specified class name
height() Sets or returns the height of selected elements
html() Sets or returns the content of selected elements
innerHeight() Returns the height of an element (includes padding, but not border)
innerWidth() Returns the width of an element (includes padding, but not border)
insertAfter() Inserts HTML elements after selected elements
insertBefore() Inserts HTML elements before selected elements
offset() Sets or returns the offset coordinates for selected elements (relative to the document)
offsetParent() Returns the first positioned parent element
outerHeight() Returns the height of an element (includes padding and border)
outerWidth() Returns the width of an element (includes padding and border)
position() Returns the position (relative to the parent element) of an element
prepend() Inserts content at the beginning of selected elements
prependTo() Inserts HTML elements at the beginning of selected elements
prop() Sets or returns properties/values of selected elements
remove() Removes the selected elements (including data and events)
removeAttr() Removes one or more attributes from selected elements
removeClass() Removes one or more classes from selected elements
removeProp() Removes a property set by the prop() method
replaceAll() Replaces selected elements with new HTML elements
replaceWith() Replaces selected elements with new content
scrollLeft() Sets or returns the horizontal scrollbar position of selected elements
scrollTop() Sets or returns the vertical scrollbar position of selected elements
text() Sets or returns the text content of selected elements
toggleClass() Toggles between adding/removing one or more classes from selected elements
unwrap() Removes the parent element of the selected elements
val() Sets or returns the value attribute of the selected elements (for form elements)
width() Sets or returns the width of selected elements
wrap() Wraps HTML element(s) around each selected element
wrapAll() Wraps HTML element(s) around all selected elements
wrapInner() Wraps HTML element(s) around the content of each selected element

jQuery Effect Methods

jQuery Effect Methods

The following table lists all the jQuery methods for creating animation effects.
Method Description
animate() Runs a custom animation on the selected elements
clearQueue() Removes all remaining queued functions from the selected elements
delay() Sets a delay for all queued functions on the selected elements
dequeue() Removes the next function from the queue, and then executes the function
fadeIn() Fades in the selected elements
fadeOut() Fades out the selected elements
fadeTo() Fades in/out the selected elements to a given opacity
fadeToggle() Toggles between the fadeIn() and fadeOut() methods
finish() Stops, removes and completes all queued animations for the selected elements
hide() Hides the selected elements
queue() Shows the queued functions on the selected elements
show() Shows the selected elements
slideDown() Slides-down (shows) the selected elements
slideToggle() Toggles between the slideUp() and slideDown() methods
slideUp() Slides-up (hides) the selected elements
stop() Stops the currently running animation for the selected elements
toggle() Toggles between the hide() and show() methods

jQuery Event Methods

jQuery Event Methods

Event methods trigger or attach a function to an event handler for the selected elements.
The following table lists all the jQuery methods used to handle events.
Method Description
bind() Attaches event handlers to elements
blur() Attaches/Triggers the blur event
change() Attaches/Triggers the change event
click() Attaches/Triggers the click event
dblclick() Attaches/Triggers the double click event
delegate() Attaches a handler to current, or future, specified child elements of the matching elements
die() Removed in version 1.9. Removes all event handlers added with the live() method
error() Deprecated in version 1.8. Attaches/Triggers the error event
event.currentTarget The current DOM element within the event bubbling phase
event.data Contains the optional data passed to an event method when the current executing handler is bound
event.delegateTarget Returns the element where the currently-called jQuery event handler was attached
event.isDefaultPrevented() Returns whether event.preventDefault() was called for the event object
event.isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was called for the event object
event.isPropagationStopped() Returns whether event.stopPropagation() was called for the event object
event.namespace Returns the namespace specified when the event was triggered
event.pageX Returns the mouse position relative to the left edge of the document
event.pageY Returns the mouse position relative to the top edge of the document
event.preventDefault() Prevents the default action of the event
event.relatedTarget Returns which element being entered or exited on mouse movement.
event.result Contains the last/previous value returned by an event handler triggered by the specified event
event.stopImmediatePropagation() Prevents other event handlers from being called
event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
event.target Returns which DOM element triggered the event
event.timeStamp Returns the number of milliseconds since January 1, 1970, when the event is triggered
event.type Returns which event type was triggered
event.which Returns which keyboard key or mouse button was pressed for the event
focus() Attaches/Triggers the focus event
focusin() Attaches an event handler to the focusin event
focusout() Attaches an event handler to the focusout event
hover() Attaches two event handlers to the hover event
keydown() Attaches/Triggers the keydown event
keypress() Attaches/Triggers the keypress event
keyup() Attaches/Triggers the keyup event
live() Removed in version 1.9. Adds one or more event handlers to current, or future, selected elements
load() Deprecated in version 1.8. Attaches an event handler to the load event
mousedown() Attaches/Triggers the mousedown event
mouseenter() Attaches/Triggers the mouseenter event
mouseleave() Attaches/Triggers the mouseleave event
mousemove() Attaches/Triggers the mousemove event
mouseout() Attaches/Triggers the mouseout event
mouseover() Attaches/Triggers the mouseover event
mouseup() Attaches/Triggers the mouseup event
off() Removes event handlers attached with the on() method
on() Attaches event handlers to elements
one() Adds one or more event handlers to selected elements. This handler can only be triggered once per element
$.proxy() Takes an existing function and returns a new one with a particular context
ready() Specifies a function to execute when the DOM is fully loaded
resize() Attaches/Triggers the resize event
scroll() Attaches/Triggers the scroll event
select() Attaches/Triggers the select event
submit() Attaches/Triggers the submit event
toggle() Removed in version 1.9. Attaches two or more functions to toggle between for the click event
trigger() Triggers all events bound to the selected elements
triggerHandler() Triggers all functions bound to a specified event for the selected elements
unbind() Removes an added event handler from selected elements
undelegate() Removes an event handler to selected elements, now or in the future
unload() Deprecated in version 1.8. Attaches an event handler to the unload event

jQuery Selectors

jQuery Selectors

Use our jQuery Selector Tester to demonstrate the different selectors.
Selector Example Selects
* $("*") All elements
#id $("#lastname") The element with id="lastname"
.class $(".intro") All elements with class="intro"
.class,.class $(".intro,.demo") All elements with the class "intro" or "demo"
element $("p") All <p> elements
el1,el2,el3 $("h1,div,p") All <h1>, <div> and <p> elements
     
:first $("p:first") The first <p> element
:last $("p:last") The last <p> element
:even $("tr:even") All even <tr> elements
:odd $("tr:odd") All odd <tr> elements
     
:first-child $("p:first-child") All <p> elements that are the first child of their parent
:first-of-type $("p:first-of-type") All <p> elements that are the first <p> element of their parent
:last-child $("p:last-child") All <p> elements that are the last child of their parent
:last-of-type $("p:last-of-type") All <p> elements that are the last <p> element of their parent
:nth-child(n) $("p:nth-child(2)") All <p> elements that are the 2nd child of their parent
:nth-last-child(n) $("p:nth-last-child(2)") All <p> elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n) $("p:nth-of-type(2)") All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n) $("p:nth-last-of-type(2)") All <p> elements that are the 2nd <p> element of their parent, counting from the last child
:only-child $("p:only-child") All <p> elements that are the only child of their parent
:only-of-type $("p:only-of-type") All <p> elements that are the only child, of its type, of their parent
     
parent > child $("div > p") All <p> elements that are a direct child of a <div> element
parent descendant $("div p") All <p> elements that are descendants of a <div> element
element + next $("div + p") The <p> element that are next to each <div> elements
element ~ siblings $("div ~ p") All <p> elements that are siblings of a <div> element
     
:eq(index) $("ul li:eq(3)") The fourth element in a list (index starts at 0)
:gt(no) $("ul li:gt(3)") List elements with an index greater than 3
:lt(no) $("ul li:lt(3)") List elements with an index less than 3
:not(selector) $("input:not(:empty)") All input elements that are not empty
     
:header $(":header") All header elements <h1>, <h2> ...
:animated $(":animated") All animated elements
:focus $(":focus") The element that currently has focus
:contains(text) $(":contains('Hello')") All elements which contains the text "Hello"
:has(selector) $("div:has(p)") All <div> elements that have a <p> element
:empty $(":empty") All elements that are empty
:parent $(":parent") All elements that are a parent of another element
:hidden $("p:hidden") All hidden <p> elements
:visible $("table:visible") All visible tables
:root $(":root") The document's root element
:lang(language) $("p:lang(de)") All <p> elements with a lang attribute value starting with "de"
     
[attribute] $("[href]") All elements with a href attribute
[attribute=value] $("[href='default.htm']") All elements with a href attribute value equal to "default.htm"
[attribute!=value] $("[href!='default.htm']") All elements with a href attribute value not equal to "default.htm"
[attribute$=value] $("[href$='.jpg']") All elements with a href attribute value ending with ".jpg"
[attribute|=value] $("[title|='Tomorrow']") All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
[attribute^=value] $("[title^='Tom']") All elements with a title attribute value starting with "Tom"
[attribute~=value] $("[title~='hello']") All elements with a title attribute value containing the specific word "hello"
[attribute*=value] $("[title*='hello']") All elements with a title attribute value containing the word "hello"
     
:input $(":input") All input elements
:text $(":text") All input elements with type="text"
:password $(":password") All input elements with type="password"
:radio $(":radio") All input elements with type="radio"
:checkbox $(":checkbox") All input elements with type="checkbox"
:submit $(":submit") All input elements with type="submit"
:reset $(":reset") All input elements with type="reset"
:button $(":button") All input elements with type="button"
:image $(":image") All input elements with type="image"
:file $(":file") All input elements with type="file"
:enabled $(":enabled") All enabled input elements
:disabled $(":disabled") All disabled input elements
:selected $(":selected") All selected input elements
:checked $(":checked") All checked input elements

jQuery Quiz Test

You can test your jQuery skills with W3Schools' Quiz.

The Test

The test contains 20 questions and there is no time limit.
The test is not official, it's just a nice way to see how much you know, or don't know, about the jQuery library.

Count Your Score

You will get 1 point for each correct answer. At the end of the Quiz, your total score will be displayed. Maximum score is 20 points.
Good luck! Start the jQuery Quiz

jQuery Examples

o you want to develop your jQuery selector skills?

jQuery Selectors

$("p").hide()
Demonstrates the jQuery hide() method, hiding all <p> elements.
$("#test").hide()
Demonstrates the jQuery hide() method, hiding the element with id="test".
$(".test").hide()
Demonstrates the jQuery hide() method, hiding all elements with class="test".
$(this).hide()
Demonstrates the jQuery hide() method, hiding the current HTML element.
Examples explained

jQuery Events

jQuery click()
Demonstrates the jQuery click() event.
jQuery dblclick()
Demonstrates the jQuery dblclick() event.
jQuery mouseenter()
Demonstrates the jQuery mouseenter() event.
jQuery mouseleave()
Demonstrates the jQuery mouseleave() event.
jQuery mousedown()
Demonstrates the jQuery mousedown() event.
jQuery mouseup()
Demonstrates the jQuery mouseup() event.
jQuery hover()
Demonstrates the jQuery hover() event.
jQuery focus() and blur()
Demonstrates the jQuery focus() and blur() events.
Examples explained

jQuery Hide/Show

jQuery hide()
Demonstrates the jQuery hide() method.
jQuery hide() and show()
Demonstrates jQuery hide() and show() methods.
jQuery toggle()
jQuery toggle() toggles between hide() and show().
jQuery hide()
Another hide demonstration. How to hide parts of text.
Examples explained

jQuery Fade

jQuery fadeIn()
Demonstrates the jQuery fadeIn() method.
jQuery fadeOut()
Demonstrates the jQuery fadeOut() method.
jQuery fadeToggle()
Demonstrates the jQuery fadeToggle() method.
jQuery fadeTo()
Demonstrates the jQuery fadeTo() method.
Examples explained

jQuery Slide

jQuery slideDown()
Demonstrates the jQuery slideDown() method.
jQuery slideUp()
Demonstrates the jQuery slideUp() method.
jQuery slideToggle()
Demonstrates the jQuery slideToggle() method.
Examples explained

jQuery Animate

jQuery animate()
Demonstrates a simple use of the jQuery animate() method.
jQuery animate() - manipulate multiple CSS properties
Demonstrates that you can manipulate multiple CSS properties with the jQuery animate() method.
jQuery animate() - using relative values
Demonstrates that you can use relative values in the jQuery animate() method.
jQuery animate() - using pre-defined values
Demonstrates that you can use the pre-defined values "hide", "show", "toggle" in the jQuery animate() method.
jQuery animate()
Demonstrates more using the jQuery animate() method (several animate() calls after each other).
jQuery animate()
Demonstrates more using the jQuery animate() method (several animate() calls after each other).
Examples explained

jQuery Stop Animations

jQuery stop() sliding
Demonstrates the jQuery stop() method.
jQuery stop() animation (with parameters)
Demonstrates the jQuery stop() method.
Examples explained

jQuery HTML Get Content and Attributes

jQuery text() and html() - Get content
Get content with the jQuery text() and html() methods.
jQuery val() - Get content
Get the value of a form field with the jQuery val() method.
jQuery attr() - Get attribute value
Get the value of an attribute with the jQuery attr() method.
Examples explained

jQuery HTML Set Content and Attributes

jQuery text(), html(), and val() - Set content
Set content with the jQuery text(), html() and val() methods.
jQuery text() and html() - Set content with a callback function
Set content + using a callback function inside text() and html().
jQuery attr() - Set attribute value
Set attribute value with the jQuery attr() method.
jQuery attr() - Set multiple attribute values
Set multiple attribute values with the jQuery attr() method.
jQuery attr() - Set attribute value with a callback function
Set attribute value + using a callback function inside attr().
Examples explained

jQuery HTML Add Elements/Content

jQuery append()
Insert content at the end of the selected HTML elements.
jQuery prepend()
Insert content at the beginning of the selected HTML elements.
jQuery append() - Insert several new elements
Create new elements with text/HTML, jQuery, and JavaScript/DOM. Then append the new elements to the text.
jQuery after() and before()
Insert content after and before the selected HTML elements.
jQuery after() - Insert several new elements
Create new elements with text/HTML, jQuery, and JavaScript/DOM. Then insert the new elements after the selected element.
Examples explained

jQuery HTML Remove Elements/Content

jQuery remove()
Remove the selected element(s).
jQuery empty()
Remove all child elements of the selected element(s).
jQuery remove() - with a parameter
Filter the elements to be removed
Examples explained

jQuery Get and Set CSS Classes

jQuery addClass()
Add class attributes to different elements.
jQuery addClass() - Multiple classes
Specify multiple classes within the addClass() method.
jQuery removeClass()
Remove a specific class attribute from different elements.
jQuery toggleClass()
Toggle between adding/removing classes from the selected elements.
Examples explained

jQuery css() Method

jQuery css() - return CSS property
Return the value of a specified CSS property from the FIRST matched element.
jQuery css() - set CSS property
Set a specified CSS property for ALL matched elements.
jQuery css() - set CSS properties
Set multiple CSS properties for ALL matched elements.
Examples explained

jQuery Dimensions

jQuery - return width() and height()
Return the width and height of a specified element.
jQuery - return innerWidth() and innerHeight()
Return the inner-width/height of a specified element.
jQuery - return outerWidth() and outerHeight()
Return the outer-width/height of a specified element.
jQuery - return outerWidth(true) and outerHeight(true)
Return the outer-width/height (including margins) of a specified element.
jQuery - return width() and height() of document and window
Return the width and height of the document (the HTML document) and window (the browser viewport).
jQuery - set width() and height()
Sets the width and height of a specified element.
Examples explained

jQuery Traversing Ancestors

jQuery parent()
Demonstrates the jQuery parent() method.
jQuery parents()
Demonstrates the jQuery parents() method.
jQuery parentsUntil()
Demonstrates the jQuery parentsUntil() method.
Examples explained

jQuery Traversing Descendants

jQuery children()
Demonstrates the jQuery children() method.
jQuery find()
Demonstrates the jQuery find() method.
Examples explained

jQuery Traversing Siblings

jQuery siblings()
Demonstrates the jQuery siblings() method.
jQuery next()
Demonstrates the jQuery next() method.
jQuery nextAll()
Demonstrates the jQuery nextAll() method.
jQuery nextUntil()
Demonstrates the jQuery nextUntil() method.
Examples explained

jQuery AJAX load() Method

jQuery load()
Load the content of a file into a <div> element.
jQuery load()
Load the content of a specific element inside a file, into a <div> element.
jQuery load() - with callback
Use of the jQuery load() method with a callback function.
Examples explained

jQuery AJAX get() and post() Methods

jQuery get()
Use the $.get() method to retrieve data from a file on the server.
jQuery post()
Use the $.post() method to send some data along with the request.
Examples explained

jQuery - The noConflict() Method

hat if you wish to use other frameworks on your pages, while still using jQuery?

jQuery and Other JavaScript Frameworks

As you already know; jQuery uses the $ sign as a shortcut for jQuery.
What if other JavaScript frameworks also use the $ sign as a shortcut?
Some other popular JavaScript frameworks are: MooTools, Backbone, Sammy, Cappuccino, Knockout, JavaScript MVC, Google Web Toolkit, Google Closure, Ember, Batman, and Ext JS.
Some of the other frameworks also use the $ character as a shortcut (just like jQuery), and then you suddenly have two different frameworks using the same shortcut, which might result in that your scripts stop working.
The jQuery team have already thought about this, and implemented the noConflict() method.

The jQuery noConflict() Method

The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.
You can of course still use jQuery, simply by writing the full name instead of the shortcut:

Example

$.noConflict();
jQuery(document).ready(function(){
  jQuery("button").click(function(){
    jQuery("p").text("jQuery is still working!");
  });
});

Try it yourself »
You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a  variable, for later use. Here is an example:

Example

var jq = $.noConflict();
jq(document).ready(function(){
  jq("button").click(function(){
    jq("p").text("jQuery is still working!");
  });
});

Try it yourself »
If you have a block of jQuery code which uses the $ shortcut and you do not want to change it all, you can pass the $ sign in as a parameter to the ready method. This allows you to access jQuery using $, inside this function - outside of it, you will have to use "jQuery":

Example

$.noConflict();
jQuery(document).ready(function($){
  $("button").click(function(){
    $("p").text("jQuery is still working!");
  });
});

Try it yourself »


jQuery Misc Reference

For a complete overview of all jQuery Misc methods, please go to our jQuery Misc Reference.

jQuery - AJAX get() and post() Methods

The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

HTTP Request: GET vs. POST

Two commonly used methods for a request-response between a client and server are: GET and POST.
  • GET - Requests data from a specified resource
  • POST - Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.
POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POST chapter.

jQuery $.get() Method

The $.get() method requests data from the server with an HTTP GET request.
Syntax:
$.get(URL,callback);
The required URL parameter specifies the URL you wish to request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the $.get() method to retrieve data from a file on the server:

Example

$("button").click(function(){
  $.get("demo_test.asp",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

Try it yourself »
The first parameter of $.get() is the URL we wish to request ("demo_test.asp").
The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like ("demo_test.asp"):
<%
response.write("This is some text from an external ASP file.")
%>


jQuery $.post() Method

The $.post() method requests data from the server using an HTTP POST request.
Syntax:
$.post(URL,data,callback);
The required URL parameter specifies the URL you wish to request.
The optional data parameter specifies some data to send along with the request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the $.post() method to send some data along with the request:

Example

$("button").click(function(){
  $.post("demo_test_post.asp",
  {
    name:"Donald Duck",
    city:"Duckburg"
  },
  function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

Try it yourself »
The first parameter of $.post() is the URL we wish to request ("demo_test_post.asp").
Then we pass in some data to send along with the request (name and city).
The ASP script in "demo_test_post.asp" reads the parameters, processes them, and returns a result.
The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like ("demo_test_post.asp"):
<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>


jQuery AJAX Reference

For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.

jQuery - AJAX load() Method

jQuery load() Method

The jQuery load() method is a simple, but powerful AJAX method.
The load() method loads data from a server and puts the returned data into the selected element.
Syntax:
$(selector).load(URL,data,callback);
The required URL parameter specifies the URL you wish to load.
The optional data parameter specifies a set of querystring key/value pairs to send along with the request.
The optional callback parameter is the name of a function to be executed after the load() method is completed.
Here is the content of our example file: "demo_test.txt":
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
The following example loads the content of the file "demo_test.txt" into a specific <div> element:

Example

$("#div1").load("demo_test.txt");

Try it yourself »
It is also possible to add a jQuery selector to the URL parameter.
The following example loads the content of the element with id="p1", inside the file "demo_test.txt", into a specific <div> element:

Example

$("#div1").load("demo_test.txt #p1");

Try it yourself »
The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
  • responseTxt - contains the resulting content if the call succeed
  • statusTxt - contains the status of the call
  • xhr - contains the XMLHttpRequest object
The following example displays an alert box after the load() method completes. If the load() method has succeed, it displays "External content loaded successfully!", and if it fails it displays an error message:

Example

$("button").click(function(){
  $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
    if(statusTxt=="success")
      alert("External content loaded successfully!");
    if(statusTxt=="error")
      alert("Error: "+xhr.status+": "+xhr.statusText);
  });
});

Try it yourself »


jQuery AJAX Reference

For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.

jQuery - AJAX Introduction

AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.

jQuery AJAX Example

Let jQuery AJAX Change This Text


Try it yourself »


What is AJAX?

AJAX = Asynchronous JavaScript and XML.
In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.
Examples of applications using AJAX: Gmail, Google Maps, Youtube, and Facebook tabs.
You can learn more about AJAX in our AJAX tutorial.


What About jQuery and AJAX?

jQuery provides several methods for AJAX functionality.
With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!
Note Without jQuery, AJAX coding can be a bit tricky!

Writing regular AJAX code can be a bit tricky, because different browsers have different syntax for AJAX implementation. This means that you will have to write extra code to test for different browsers. However, the jQuery team has taken care of this for us, so that we can write AJAX functionality with only one single line of code.


jQuery AJAX Methods

In the next chapters we will look at the most important jQuery AJAX methods.

jQuery Traversing - Filtering

Narrow Down The Search For Elements

The three most basic filtering methods are first(), last() and eq(), which allow you to select a specific element based on its position in a group of elements.
Other filtering methods, like filter() and not() allow you to select elements that match, or do not match, a certain criteria.

jQuery first() Method

The first() method returns the first element of the selected elements.
The following example selects the first <p> element inside the first <div> element:

Example

$(document).ready(function(){
  $("div p").first();
});

Try it yourself »


jQuery last() Method

The last() method returns the last element of the selected elements.
The following example selects the last <p> element inside the last <div> element:

Example

$(document).ready(function(){
  $("div p").last();
});

Try it yourself »


jQuery eq() method

The eq() method returns an element with a specific index number of the selected elements.
The index numbers start at 0, so the first element will have the index number 0 and not 1. The following example selects the second <p> element (index number 1):

Example

$(document).ready(function(){
  $("p").eq(1);
});

Try it yourself »


jQuery filter() Method

The filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.
The following example returns all <p> elements with class name "intro":

Example

$(document).ready(function(){
  $("p").filter(".intro");
});

Try it yourself »


jQuery not() Method

The not() method returns all elements that do not match the criteria.
Tip: The not() method is the opposite of filter().
The following example returns all <p> elements that do not have class name "intro":

Example

$(document).ready(function(){
  $("p").not(".intro");
});

Try it yourself »


jQuery Traversing Reference

For a complete overview of all jQuery Traversing methods, please go to our jQuery Traversing Reference.

jQuery Traversing - Siblings

Siblings share the same parent.
With jQuery you can traverse sideways in the DOM tree to find siblings of an element.

Traversing Sideways in The DOM Tree

There are many useful jQuery methods for traversing sideways in the DOM tree:
  • siblings()
  • next()
  • nextAll()
  • nextUntil()
  • prev()
  • prevAll()
  • prevUntil()

jQuery siblings() Method

The siblings() method returns all sibling elements of the selected element.
The following example returns all sibling elements of <h2>:

Example

$(document).ready(function(){
  $("h2").siblings();
});

Try it yourself »
You can also use an optional parameter to filter the search for siblings.
The following example returns all sibling elements of <h2> that are <p> elements:

Example

$(document).ready(function(){
  $("h2").siblings("p");
});

Try it yourself »


jQuery next() Method

The next() method returns the next sibling element of the selected element.
The following example returns the next sibling of <h2>:

Example

$(document).ready(function(){
  $("h2").next();
});

Try it yourself »


jQuery nextAll() Method

The nextAll() method returns all next sibling elements of the selected element.
The following example returns all next sibling elements of <h2>:

Example

$(document).ready(function(){
  $("h2").nextAll();
});

Try it yourself »


jQuery nextUntil() Method

The nextUntil() method returns all next sibling elements between two given arguments.
The following example returns all sibling elements between a <h2> and a <h6> element:

Example

$(document).ready(function(){
  $("h2").nextUntil("h6");
});

Try it yourself »


jQuery prev(), prevAll() & prevUntil() Methods

The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).

jQuery Traversing Reference

For a complete overview of all jQuery Traversing methods, please go to our jQuery Traversing Reference.

jQuery Traversing - Descendants

A descendant is a child, grandchild, great-grandchild, and so on.
With jQuery you can traverse down the DOM tree to find descendants of an element.

Traversing Down the DOM Tree

Two useful jQuery methods for traversing down the DOM tree are:
  • children()
  • find()

jQuery children() Method

The children() method returns all direct children of the selected element.
This method only traverse a single level down the DOM tree.
The following example returns all elements that are direct children of each <div> elements:

Example

$(document).ready(function(){
  $("div").children();
});

Try it yourself »
You can also use an optional parameter to filter the search for children.
The following example returns all <p> elements with the class name "1", that are direct children of <div>:

Example

$(document).ready(function(){
  $("div").children("p.1");
});

Try it yourself »


jQuery find() Method

The find() method returns descendant elements of the selected element, all the way down to the last descendant.
The following example returns all <span> elements that are descendants of <div>:

Example

$(document).ready(function(){
  $("div").find("span");
});

Try it yourself »
The following example returns all descendants of <div>:

Example

$(document).ready(function(){
  $("div").find("*");
});

Try it yourself »


jQuery Traversing Reference

For a complete overview of all jQuery Traversing methods, please go to our jQuery Traversing Reference.

jQuery Traversing - Ancestors

An ancestor is a parent, grandparent, great-grandparent, and so on.
With jQuery you can traverse up the DOM tree to find ancestors of an element.

Traversing Up the DOM Tree

Three useful jQuery methods for traversing up the DOM tree are:
  • parent()
  • parents()
  • parentsUntil()

jQuery parent() Method

The parent() method returns the direct parent element of the selected element.
This method only traverse a single level up the DOM tree.
The following example returns the direct parent element of each <span> elements:

Example

$(document).ready(function(){
  $("span").parent();
});

Try it yourself »


jQuery parents() Method

The parents() method returns all ancestor elements of the selected element, all the way up to the document's root element (<html>).
The following example returns all ancestors of all <span> elements:

Example

$(document).ready(function(){
  $("span").parents();
});

Try it yourself »
You can also use an optional parameter to filter the search for ancestors.
The following example returns all ancestors of all <span> elements that are <ul> elements:

Example

$(document).ready(function(){
  $("span").parents("ul");
});

Try it yourself »


jQuery parentsUntil() Method

The parentsUntil() method returns all ancestor elements between two given arguments.
The following example returns all ancestor elements between a <span> and a <div> element:

Example

$(document).ready(function(){
  $("span").parentsUntil("div");
});

Try it yourself »


jQuery Traversing Reference

For a complete overview of all jQuery Traversing methods, please go to our jQuery Traversing Reference.

jQuery Traversing

What is Traversing?

jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire.
The image below illustrates a family tree. With jQuery traversing, you can easily move up (ancestors), down (descendants) and sideways (siblings) in the family tree, starting from the selected (current) element. This movement is called traversing - or moving through - the DOM.
jQuery Dimensions
Illustration explained:
  • The <div> element is the parent of <ul>, and an ancestor of everything inside of it
  • The <ul> element is the parent of both <li> elements, and a child of <div>
  • The left <li> element is the parent of <span>, child of <ul> and a descendant of <div>
  • The <span> element is a child of the left <li> and a descendant of <ul> and <div>
  • The two <li> elements are siblings (they share the same parent)
  • The right <li> element is the parent of <b>, child of <ul> and a descendant of <div>
  • The <b> element is a child of the right <li> and a descendant of <ul> and <div>

Note An ancestor is a parent, grandparent, great-grandparent, and so on.
A descendant is a child, grandchild, great-grandchild, and so on.
Siblings share the same parent.


Traversing the DOM

jQuery provides a variety of methods that allows us to traverse the DOM.
The largest category of traversal methods are tree-traversal.
The next chapters will show us how to travel up, down and sideways in the DOM tree.

jQuery Traversing Reference

For a complete overview of all jQuery Traversing methods, please go to our jQuery Traversing Reference.

jQuery - Dimensions

With jQuery, it is easy to work with the dimensions of elements and browser window.

jQuery Dimension Methods

jQuery has several important methods for working with dimensions:
  • width()
  • height()
  • innerWidth()
  • innerHeight()
  • outerWidth()
  • outerHeight()

jQuery Dimensions

jQuery Dimensions

jQuery width() and height() Methods

The width() method sets or returns the width of an element (includes NO padding, border, or margin).
The height() method sets or returns the height of an element (includes NO padding, border, or margin).
The following example returns the width and height of a specified <div> element:

Example

$("button").click(function(){
  var txt="";
  txt+="Width: " + $("#div1").width() + "</br>";
  txt+="Height: " + $("#div1").height();
  $("#div1").html(txt);
});

Try it yourself »


jQuery innerWidth() and innerHeight() Methods

The innerWidth() method returns the width of an element (includes padding).
The innerHeight() method returns the height of an element (includes padding).
The following example returns the inner-width/height of a specified <div> element:

Example

$("button").click(function(){
  var txt="";
  txt+="Inner width: " + $("#div1").innerWidth() + "</br>";
  txt+="Inner height: " + $("#div1").innerHeight();
  $("#div1").html(txt);
});

Try it yourself »


jQuery outerWidth() and outerHeight() Methods

The outerWidth() method returns the width of an element (includes padding and border).
The outerHeight() method returns the height of an element (includes padding and border).
The following example returns the outer-width/height of a specified <div> element:

Example

$("button").click(function(){
  var txt="";
  txt+="Outer width: " + $("#div1").outerWidth() + "</br>";
  txt+="Outer height: " + $("#div1").outerHeight();
  $("#div1").html(txt);
});

Try it yourself »
The outerWidth(true) method returns the width of an element (includes padding, border, and margin).
The outerHeight(true) method returns the height of an element (includes padding, border, and margin).

Example

$("button").click(function(){
  var txt="";
  txt+="Outer width (+margin): " + $("#div1").outerWidth(true) + "</br>";
  txt+="Outer height (+margin): " + $("#div1").outerHeight(true);
  $("#div1").html(txt);
});

Try it yourself »


jQuery More width() and height()

The following example returns the width and height of the document (the HTML document) and window (the browser viewport):

Example

$("button").click(function(){
  var txt="";
  txt+="Document width/height: " + $(document).width();
  txt+="x" + $(document).height() + "\n";
  txt+="Window width/height: " + $(window).width();
  txt+="x" + $(window).height();
  alert(txt);
});

Try it yourself »
The following example sets the width and height of a specified <div> element:

Example

$("button").click(function(){
  $("#div1").width(500).height(500);
});

Try it yourself »


jQuery CSS Reference

For a complete overview of all jQuery CSS methods, please go to our jQuery HTML/CSS Reference.

jQuery - css() Method

jQuery css() Method

The css() method sets or returns one or more style properties for the selected elements.

Return a CSS Property

To return the value of a specified CSS property, use the following syntax:
css("propertyname");
The following example will return the background-color value of the FIRST matched element:

Example

$("p").css("background-color");

Try it yourself »


Set a CSS Property

To set a specified CSS property, use the following syntax:
css("propertyname","value");
The following example will set the background-color value for ALL matched elements:

Example

$("p").css("background-color","yellow");

Try it yourself »


Set Multiple CSS Properties

To set multiple CSS properties, use the following syntax:
css({"propertyname":"value","propertyname":"value",...});
The following example will set a background-color and a font-size for ALL matched elements:

Example

$("p").css({"background-color":"yellow","font-size":"200%"});

Try it yourself »


jQuery CSS Reference

For a complete overview of all jQuery CSS methods, please go to our jQuery HTML/CSS Reference.