Home > Articles > Web Development > Ajax and JavaScript

  • Print
  • + Share This
Like this article? We recommend jQuery Selectors

jQuery Selectors

The principles of jQuery are astonishingly simple: You can use CSS or XPath selectors (augmented with a few things that we've always wanted to have in CSS) to select a set of web page objects. After you've selected your set, you can refine it, extend it, filter it, find its parents (or children) or execute a number of methods (set a class, display or hide the object, set a CSS parameter, and so forth) on all members of the set.

The main jQuery function (jQuery()) finds the DOM objects you want. It's also available as a shortcut ($()), resulting in very concise code. For example, to save the set of all paragraphs in your page into a variable, use this code:

var allParas = $('P');

Likewise, you can find all links within the header DIV with a very simple call:

var links = $('DIV#header A');

The selectors can get pretty complex. You can find all external links with the ^= (attribute starts with text) test:

$('A[href^=http:]');

Sometimes you want to select a set of objects for which there is no readily available selector. No problem; you can use the find method to perform multiple tests in sequence. For example, if you want to find paragraphs with links within DIV blocks that don't have H1 headings, the following code sequence will give you the desired results:

$('DIV:not(H1)').find('P[A]')
  • + Share This
  • 🔖 Save To Your Account