jQuery Index Based Selectors

So this post is not really strictly SharePoint. But covers a cool function I hadn’t noticed before in jQuery, namely it supports CSS3 index based selectors. I was asked to make it so in a MOSS2007 item display form for a single URL field to automatically open in a new window. Previously when I’ve done jQuery on the edit form I’d used the [title=”Field Name”] to select the correct row but was surprised to notice the display forms do not have this attribute added to the table at all. Plan two was lets grab the td#SPFieldURL as a selector except this does all fields that just display a URL so this was a no go. After digging further I noticed that jQuery supports tag:nth-body(n) as a selector. For those unfamiliar with nth-body it’s a new CSS3 selector that can select a tag by it’s relative index. It can also do nifty things like (3n+3) which selects every third occurrence of a specific tag.

So in my case, to just have the second field’s URL value always open in a new window I did this:

$(‘table.ms-formtable > tbody > tr:nth-child(2) > td.ms-formbody > a’).attr(“target”, “_blank”);

This did all the magic I needed in this case. 😀 Additionally because it’s being used within jQuery rather than within a style tag browser compliance with CSS3 *cough internet explorer cough* isn’t an issue.

  1. No comments yet.
(will not be published)

%d bloggers like this: