Nov 7, 2009

Selecting elements with JQuery – examples

JQuery Library is a very convenient way for selecting page elements. You can select elements by type, by parent, by index and so on.
The easiest way to select an item is by its id. I’ll use it for my control buttons. For all three of them I’ll bind functions to their click event.
Here are my buttons as HTML code:

<button id="all">Show/Hide ALL</button>
<button id="nth">Show/Hide nth</button>
<button id="odd">Show/Hide ODD</button>

And my test javascript code here:

$(document).ready(function() {
 $("#all").click(function () {
  alert("Clicked ALL");
 });
 $("#nth").click(function () {
  alert("Clicked NTH");
 });
 $("#odd").click(function () {
  alert("Clicked ODD");
 });
});

Now we will change the code to select and toggle the desired elements. We will start with the first because it is the easiest of them all. Selecting elements by type in JQuery is very simple and is done through their name. To select all paragraphs we simply need to use $("p") and call toggle on it. $("p") will return all matched elements – all ‘p’ tags on the page.
The code:
$("#all").click(function () {
 $("p").toggle();
});

To select the n-th element – in our case the third one we will use $("p:eq(3)") and to select all odd paragraphs $("p:odd").

Here is the full example code:
<html>
<head>
<title>Selecting elements with JQuery</title>
<script  src="jquery.js"></script>

<script>
$(document).ready(function() {
 $("#all").click(function () {
  $("p").toggle();
 });
 $("#nth").click(function () {
  $("p:eq(3)").toggle();
 });
 $("#odd").click(function () {
  $("p:odd").toggle();
 });
});
</script>
</head>
<body>
JQuery example - selecting items.
<div>
<p>Paragraph 0</p>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</div>
<div>
<table>
<tr><td>All Paragraphs: </td><td><button id="all">Show/Hide ALL</button></td></tr>
<tr><td>Third paragraph: </td><td><button id="nth">Show/Hide nth</button></td></tr>
<tr><td>All odd paragraphs: </td><td><button id="odd">Show/Hide ODD</button></td></tr>
</table>
</div>
</body>
</html>

As you can see – very simple and intuitive.

No comments:

Popular Posts