August 31, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

10 Ways to Find the Web Elements You're Looking For with jQuery

  • May 17, 2010
  • By Jason Gilmore
  • Send Email »
  • More Articles »

jQuery's fantastic array of features allows you to do what often seems impossible with standard JavaScript syntax. The popular open source JavaScript library's capabilities are particularly strong when it comes to parsing and manipulate the DOM. In this tutorial, I'll demonstrate 10 useful ways you can use jQuery to parse a Web page, ranging from locating the most obvious elements to ferreting out those buried deep within the DOM.

1. Finding Elements by Their HTML Tag

The most fundamental parsing task involves finding all page elements of a specific HTML tag type. For instance, suppose you wanted to toggle the visibility of all unordered lists found within a page. You might assign an event handler to a link or button that has been assigned a class named toggle-lists. When clicked, you would pass ul to the jQuery selector, simultaneously executing the toggle() method on all of them, as demonstrated here:

$(".toggle-lists").click(function() {
  $("ul").toggle();
  $(this).text( $(this).text() == "Show lists" ? "Hide lists" : "Show lists");
  return false;
})


2. Finding an Element by Its ID

Finding an element by its ID is really no different from finding elements according to their HTML tag types; all you need to do is pass the element ID to the selector syntax. For instance, suppose you wanted to retrieve the content found within an element identified by ID 45. You would use the following syntax:

$("#45").text();


Consider a more involved example, where you first find an element based on its tag type and then narrow down the selection according to the element's ID. Suppose you wanted to create an event handler that toggles between formatted code and plaintext within a pre tag enclosure when the user clicked within a particular code sample. This functionality would allow the user to more easily copy and paste the text into a code editor. To do this, you'd need to assign a unique ID to each sample, meaning each code sample would look like this:

<pre id="45" class="code-formatted">
<?php
  public function init()
  {
      $this->session = new Zend_Session_Namespace('Developer');
  }
?>
</pre>


You can accomplish this task by creating a click handler that is attached to all of the document's pre tags. When executed, you would retrieve the DIV value and then switch the CSS class to one that removes the special formatting:

$("pre").click(function() {
  id = $(this).attr("id");
  $("#" + id).toggleClass('code-plain', 'code-formatted');
  return false;
})


3. Finding an Element's Children

Previously you learned how to easily select all elements associated with a particular HTML tag such as ul (unordered list). But what if you wanted to select only elements fitting a certain criteria, such as only those list items nested within a ul tag identified by the ID recipe? For instance, that list might look like this:

<ul id="recipe">
<li>3 green plantains, peeled and chopped</li>
<li>4 tablespoons olive oil</li>
<li>3-4 cloves garlic</li>
<li>1 green pepper cut into large chunks</li>
</ul>


Obtaining this list's items using jQuery is easier than you might think:

ingredients = $("#recipe > li");


4. Finding an Element's Parent

Now, suppose you wanted to identify the parent of a particular element. For instance, you wanted to highlight an entire table row when the user clicks a checkbox associated with the row, as depicted in Figure 1.

In this case, you'd actually be looking for the parent's parent because the checkbox resides in a table cell that forms part of the row you'd like to highlight. JQuery supports a number of solutions for traversing a DOM element's ancestry. However, for your purposes, the easiest approach is to use the closest() method. The closest() method will start searching up the ancestry tree, searching for a predetermined element and halting the search the very first time that an ancestor element is located. This example implements the task of highlighting a checked checkbox row:

$("input[name=download[]]").change(function() {
  if ($("input[name=download[]]:checked").val()) {
    var tr = $(this).closest('tr');
    tr.addClass('highlight');
  } else {
    var tr = $(this).closest('tr');
    tr.removeClass('highlight');
  }
})


5. Narrowing Your Search

Suppose you created a feature that asks the user to reorder a list of video games according to preference. When the reordering is complete, you'd like to send information for the top three choices back to the server for further processing. That list might look like this:

<p>Order the list of video games according to preference:</p>
<ul>
<li>PacMan</li>
<li>Ikari Warriors</li>
<li>Alien Syndrome</li>
<li>Burger Time</li>
<li>Space Invaders</li>
</ul>


To retrieve just the first three list items, use the lt selector:

var favoriteGames = $('li:lt(3)');



Tags: Web development, JavaScript, jQuery, search



Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel