02.06.2013 Views

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Within the function you pass to filter(), you can refer to the current element via the<br />

this keyword. To make it into a <strong>jQuery</strong> object (so you can access and perform <strong>jQuery</strong><br />

methods), simply wrap it in the <strong>jQuery</strong> function:<br />

this; // Regular element object<br />

<strong>jQuery</strong>(this); // <strong>jQuery</strong> object<br />

Here are some other filtering examples to spark your imagination:<br />

// Select all DIV elements with a width between 100px and 200px:<br />

<strong>jQuery</strong>('div').filter(function(){<br />

var width = <strong>jQuery</strong>(this).width();<br />

return width > 100 && width < 200;<br />

});<br />

// Select all images with a <strong>com</strong>mon image extension:<br />

<strong>jQuery</strong>('img').filter(function(){<br />

return /\.(jpe?g|png|bmp|gif)(\?.+)?$/.test(this.src);<br />

});<br />

// Select all elements that have either 10 or 20 children:<br />

<strong>jQuery</strong>('*').filter(function(){<br />

var children = <strong>jQuery</strong>(this).children().length;<br />

return children === 10 || children === 20;<br />

});<br />

Discussion<br />

There will always be several different ways to do something; this is no less true when<br />

selecting elements with <strong>jQuery</strong>. The key differential is usually going to be speed; some<br />

ways are fast, others are slow. When you use a <strong>com</strong>plicated selector, you should be<br />

thinking about how much processing <strong>jQuery</strong> has to do in the background. A longer<br />

and more <strong>com</strong>plex selector will take longer to return results. <strong>jQuery</strong>’s native methods<br />

can sometimes be much faster than using a single selector, plus there’s the added benefit<br />

of readability. Compare these two techniques:<br />

<strong>jQuery</strong>('div a:not([href^=http://]), p a:not([href^=http://])');<br />

<strong>jQuery</strong>('div, p').find('a').not('[href^=http://]');<br />

The second technique is shorter and much more readable than the first. Testing in<br />

Firefox (v3) and Safari (v4) reveals that it’s also faster than the first technique.<br />

2.11 Using the Context Parameter<br />

Problem<br />

You’ve heard of the context parameter but have yet to encounter a situation where it’s<br />

useful.<br />

48 | Chapter 2: Selecting Elements with <strong>jQuery</strong>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!