Tyler Muth’s Blog

Technology with a focus on Oracle, Application Express and Linux

jQuery Custom Selector

Posted by Tyler Muth on March 23, 2011

I’m working on a little Google Chrome Extension in my spare time to add a little formatting and bells and whistles to AWR Reports like converting Physical/Logical Reads/Consistent gets and bytes to KB/MB/GB. Also adding sorting and filtering to key tables, as well as making all wait events “hot” with a popup to show there definition, etc. Anyway, I found myself writing the same logic in a jQuery selectors all throughout my code to find the section headings of the report. Essentially, they’re either a p, h2, or h3 that contain text, have no child elements, and are a first-child of body. So, I wrote a custom selector to encapsulate the logic and drastically reduce and simplify my code:

jQuery.expr[':'].topLevelTextElement = function(element, index) {
     // if there is only one child, and it is a text node (<div>hello world</div>, not <div><span>hello world</span></div>)
     if (element.childNodes.length == 1 && element.firstChild.nodeType == 3) {
		// if it's parent is the <body> tag, ie it's not nested several levels deep
		if(element.parentNode.nodeName == 'BODY'){
			return jQuery.trim(element.innerHTML).length > 0;
     return false;

Here are some examples of it in action:

// iterate over each element the selector finds and log what type of node (tag) it is.
//console output:

// iterate over each h2 element the selector finds and log the text it contains
//console output:
//Main Report
//More RAC Statistics
//Wait Events Statistics

On a related note, if you know JavaScript, CSS, and HTML, writing a Google Chrome Extension is REALLY easy. The documentation and examples are still a little weak. Integrating jQuery, jQuery Plugins, and jQuery UI was also quite easy, but there’s a minor catch for image references in CSS in that relative paths don’t work (easily). You have to use your extension name as an absolute path. I’ll blog about this later. If you need it now, just ask…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: