Ad

Ad

Monday, 5 May 2014

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.