02.06.2013 Views

DOM Traversal Methods

DOM Traversal Methods

DOM Traversal Methods

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

[ 59 ]<br />

Chapter 3<br />

This chain searches for items with the class foo within the first list only and adds the<br />

class some-class to them. Then .end() returns the object to its state before the call<br />

to .find(), so the second .find() looks for .bar inside , not<br />

just inside that list's , and adds the class another-class to the<br />

matching element. The result is that items 1 and 3 of the first list have a class added<br />

to them, and none of the items from the second list do.<br />

A long jQuery chain can be visualized as a structured code block, with filtering<br />

methods providing the openings of nested blocks and .end methods closing them:<br />

$('#example-traversing-end ul.first').find('.foo')<br />

.addClass('some-class')<br />

.end()<br />

.find('.bar')<br />

.addClass('another-class');<br />

.end();<br />

The last .end() is unnecessary, as we are discarding the jQuery object immediately<br />

thereafter. However, when the code is written in this form the .end() provides<br />

visual symmetry and closure—making the program, at least to the eyes of some<br />

developers, more readable.

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

Saved successfully!

Ooh no, something went wrong!