Easy jQuery

Blog about jQuery - next generation JavaScript library.

Oct
4

Selectors - Part II.

AlexGeneral


Basic filters.

:first - select first element.
This code will set font to italic on first row of the table:

$("tr:first").css("font-style","italic");

Open this example in new window and view source code.

:last - select last element
This code will select the last row of table and set background color to yellow and font to bold:

$("tr:last").css({
  backgroundColor: "yellow",
  fontWeight: "bolder"
});

Open this example in new window and view source code.

:not(selector) - select all elements which has not filtered by selector.
This code select all spans on the page that have not class “myclass” and set their background color to red:

$(":not(.myclass) + span").css("background-color","red");

Open this example in new window and view source code.

:even - select all even elements, zero-indexed.
This code select all even table rows and set their background color to red:

$("tr:even").css("background-color","red");

Open this example in new window and view source code.

:odd - select all odd elements, zero-indexed.
This code select all odd table rows and set their background color to red:

$("tr:odd").css("background-color","red");

Open this example in new window and view source code.

:eq(index) - select single element by index, zero-indexed.
This code select second cell in a table and set their background color to red:

$("td:eq(2)").css("background-color","red");

Open this example in new window and view source code.

:gt(index) - select elements with index, greater than given one, zero-indexed.
This code select all cells in a table with index greater than 3 and set their background color to red:

$("gt:eq(3)").css("background-color","red");

Open this example in new window and view source code.

:lt(index) - select elements with index, below than given one, zero-indexed.
This code select all cells in a table with index less than 3 and set their background color to red:

$("gt:lt(3)").css("background-color","red");

Open this example in new window and view source code.

:header - select all header on the page (h1, h2, …).
This code select all headers and set their font color to blue:

$(":header").css("color","blue");

Open this example in new window and view source code.

:animated - select all currently animated elements on page.
This code select change color of any div, beeng animated:

$("#run").click(function(){
      $("div:animated").toggleClass("colored");
});
function animateIt() {
      $("#mover").slideToggle("slow", animateIt);
}
animateIt();

Open this example in new window and view source code.

Add A Comment