09.02.2015 Views

DOM Traversal Methods - MarkMail

DOM Traversal Methods - MarkMail

DOM Traversal Methods - MarkMail

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9<br />

});<br />

};<br />

.text(message)<br />

.hide()<br />

.appendTo(this)<br />

.fadeIn();<br />

Now calling $('.log').log('foo') has the effect our global function call did<br />

previously, but we can change the selector expression to target different log boxes.<br />

Ideally, though, the .log method would be intelligent enough to locate the most<br />

relevant box to use for the log message without an explicit selector. By exploiting the<br />

context passed to the method, we can traverse the <strong>DOM</strong> to find the log box nearest<br />

the selected element:<br />

jQuery.fn.log = function(message) {<br />

return this.each(function() {<br />

$context = $(this);<br />

while ($context.length) {<br />

$log = $context.find('.log');<br />

if ($log.length) {<br />

$('')<br />

.text(message).hide().appendTo($log).fadeIn();<br />

break;<br />

}<br />

$context = $context.parent();<br />

}<br />

});<br />

};<br />

This code looks for a log message box within the matched elements, and if none is<br />

found, walks up the <strong>DOM</strong> in search of one.<br />

Finally, at times we require the ability to display the contents of an object. Printing<br />

out the object itself yields something barely informative like [object Object], so<br />

we can detect the argument type and do some of our own pretty-printing in the case<br />

that an object is passed in:<br />

jQuery.fn.log = function(message) {<br />

if (typeof(message) == 'object') {<br />

string = '{';<br />

$.each(message, function(key, value) {<br />

string += key + ': ' + value + ', ';<br />

});<br />

string += '}';<br />

message = string;<br />

[ 193 ]

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

Saved successfully!

Ooh no, something went wrong!