6 more jQuery Tips: Text Searching, Page Load Time and Others
Posted 2008-07-22 in JavaScript by Johann.
After the first and the second round of jQuery tips, here are 6 more JavaScript snippets.
Searching for Text with jQuery
This function performs a recursive search for nodes that contain a pattern. Arguments are a jQuery object and a pattern. The pattern can be a string
or a regular expression.
$.fn.egrep = function(pat) { var out = []; var textNodes = function(n) { if (n.nodeType == Node.TEXT_NODE) { var t = typeof pat == 'string' ? n.nodeValue.indexOf(pat) != -1 : pat.test(n.nodeValue); if (t) { out.push(n.parentNode); } } else { $.each(n.childNodes, function(a, b) { textNodes(b); }); } }; this.each(function() { textNodes(this); }); return out; };
Demo: Highlight all nodes containing a text node that contains the word “jQuery”.
Case-Insensitive Contains Check
By using case-insensitive regular expressions, this becomes rather easy:
var pattern = /exp/i; $('#id').filter(function() { return pattern.test($(this).text()); });
Demo: Turn all list items that contain “bla” bold.
- Blabla
- Keks
- BLA
Super small jquery.js
Many people want an even smaller version of jQuery. The combination of YUI and JavaScript Utility yields a 26807 B jquery-1.2.6.js
file which is almost 15 % smaller than the regular size of 31033 B.
Log Page Load Time
With large pages or pages containing inline JavaScript, it is a good idea™ to monitor how long pages take to load. The code below is different from waiting until onload
is fired and only measures page load time.
<html> <head> <script type="text/javascript"> var t = new Date(); </script> … (your page) … <script type="text/javascript"> new Image().src = '/load.gif?' + (new Date().getTime() - t.getTime()); </script> </body> <html>
load.gif
can be a generic 1*1 pixel GIF. You can extract the data from your log files using grep
and sed
.
Reload an IFrame
Accessing the contentWindow
property to obtain the location
object.
$('#iframe').each(function() { this.contentWindow.location.reload(true); });
Demo: Force a reload of the IFrame
below.
Callback for IFrame
Loading
With the onload
event, your code is called when an IFrame
has finished loading.
$('#iframe').load(function() { // do something });
Demo: Force a reload of the IFrame
below.
I hope you find these tips useful.
Subscribe
RSS 2.0, Atom or subscribe by Email.
Top Posts
- DynaCloud - a dynamic JavaScript tag/keyword cloud with jQuery
- 6 fast jQuery Tips: More basic Snippets
- xslt.js version 3.2 released
- xslt.js version 3.0 released XML XSLT now with jQuery plugin
- Forum Scanners - prevent forum abuse
- Automate JavaScript compression with YUI Compressor and /packer/