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

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

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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)');

6. Finding an Element by an Attribute

Suppose you created a website that allowed teachers to post their lesson plans online for others. These plans often reference third-party online PDF- and Excel-based resources. For instance, a lesson snippet might look like this:

If you'd like to carry out your own physics experiments, check out the e-book, 
<a href="http://www.example.com/lab.pdf">"Building Your Own Lab"</a>.

Because of the posted lessons’ free-form nature, it’s not easy to create server-side solutions that can parse the document for a list of all PDF links — a task that might be useful for creating lesson summaries identifying third-party resources. However, performing this task with jQuery is trivial:

var pdfs = $('a[href$=pdf]');
$.each(pdfs, function(index, item) {
  $("#externals").append(item + "<br />");
});

7. Filtering Your Selections

Suppose you created an online recipe repository with the feature of e-mailing users only those recipe ingredients that aren’t already available at their homes. The feature determines which ingredients need to be purchased by allowing the user to click on those list items he knows he already owns. Each click adds a class named selected to the ingredient. When complete, the code retrieves only those list items not associated with the selected class. You can accomplish this task using the :not() selector:

var ingredients = $("li:not('.selected')");

8. Retrieving Form Values

Earlier you learned how to use the :checked selector to detect whether a checkbox was checked. But how would you retrieve the value of, for instance, a particular text input? You actually use syntax quite similar to that used in the earlier example, additionally using the val() method to retrieve the input:

var email = $("input[name=email]").val();

9. Finding Elements Containing Text

A site that offers users searchable indexes of documents might make keyword searches more convenient by highlighting paragraphs containing the sought after term. You can use the :contains() selector to easily associate a class with all paragraphs containing the keyword:

$("p:contains('NASA')").addClass("highlight");

10. Using jQuery’s Custom Selectors

Developers often need to select DOM elements based on criteria that are not easily accessible using standard JavaScript. Recognizing that, jQuery offers a number of custom selectors capable of performing tasks such as retrieving all checkboxes or radio buttons that are currently checked:

var checked = $(':checked');

JQuery supports a number of other custom selectors, capable of retrieving all checkboxes (checked or otherwise), header elements (h1, h2, etc.), button elements, and others.

Conclusion

JQuery’s powerful selector syntax makes retrieving any page element a trivial task! What other jQuery features do you like best? Tell us about them in the comments.

About the Author


Jason Gilmore is the founder of EasyPHPWebsites.com. He also is the author of several popular books, including “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Third Edition”.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories