Selectors in jQuery
In this tutorial i’ll go over some of the frequently used Selectors and show you how to use them. Most of jQuery’s manipulations revolve around selectors, so it’s a vital skill to know.
| One | Two | Three | Four | Five |
So.. we want to select the first td. We do this by first selecting all the td tags and then use :first to select the first td. Using jQuery’s great chaining ability, we change the text.
$("td:first").text("This is the altered first box");
jQuery also has
dd and :even selectors. This will select the odd or even id’s. In this next example. We are selecting all of the odd td‘s , and then select the first one of them. Again , we use jQuery’s chainability.
$("td:odd:first").text("We changed this using odd and first");
You need to be aware that selecting the odds/evens does not use the element ids. It just counts them. It starts from 0 and starts counting, not from 1. This is why it changes the second cell using the method above.
Now, lets match the next one by specific text. We can do this using the :contains selector. We look in all td elements, then in them we look for the word Three , if we find it we replace the text.
$("td:contains('Three')").text("we matched the text, then changed it.");
We can use the element id to edit select what we want. jQuery’s element selector is the hash symbol (#).
$("#4").text("We found this using the id");
The last one! How are we going to select it? We are going to use the gt selector. We can specify a tag, and jQuery counts how many there are. In this case we select td and it counts them (remember it starts at 0, not 1). It will select all the td that are higher than the number we specify. So we have 5 td , 0,1,2,3,4 . Se specify number 3, so only number 4 is effected. Thats our last td.
$("td:gt(3)").text("The Last One!");

