How to Get Anything You Want - part 1
With jQuery, you can get to just about anything on a web page. In this entry, I’ll show you a few ways you can use jQuery’s versatile selector expressions to traverse to an element — or group of elements — in the DOM.
I’ve put together a short paragraph and an ordered list scattered with inline elements such as <em>, <code>, and links. It’s all wrapped in a DIV with an ID of “jqdt,” which allows me to focus the demonstration to one area of this page.
Each button below the “jqdt” DIV will toggle a yellow background on and off for the parts of the DIV described.
This is a paragraph of text with class=”goofy.” It has an external link, some $(code), and a same-page link.
-
$('li:eq(0)')gets the first list item -
$('li:even')gets all odd-numbered list items (because, in javascript, numbering starts with 0, not 1). -
$('li:lt(3)')gets the first 3 list items. “lt” stands for “less than,” and it starts counting at 0, not 1. -
$('li:not(.goofy)')gets list items 1, 2, and 4, because they’re not “goofy.” -
$('p a[@href*=#]')gets any links that are inside a paragraph and have an “href” attributestarting with “#” —containing “#” anywhere.in other words, same-page links. There are problems with trying to identify same-page links this way. I’ll write about this in an upcoming entry. Note the space between the “p” and the “a”; that means that the “a” is a descendant of the “p.” -
$('code, li.goofy')gets all code elements and any list item with a class of “goofy.” -
$('ol .goofy > strong')gets all strong elements that are children of any element with a class of “goofy” as long as the class somewhere inside (i.e. a descendent) of an ordered list. Notice that the word “item” is not highlighted because, even though it’s inside “.goofy,” it’s not a direct child. Only “goofy” is a direct child of “.goofy.” Maybe we should call it “goofy jr.” -
$('li + li > a[@href$=pdf]')gets all links ending in “pdf” that are children of any list item that has another list item as its previous sibling. It won’t get the first list item’s silly.pdf because that list item has no other list items before it. -
$('span:hidden')gets any span element that is hidden.
Note: The selectors used for the toggle buttons are identical to the ones shown next to each button, except that they are preceded by $('#jqdt').find to target the highlighting.
jQuery’s selector expressions cover the full range of CSS 1-3, along with basic XPath and a few jQuery-only expressions. For a complete list, visit jquery.com
Next time, I’ll explore jQuery functions such as .filter(), prev(), and siblings() that complement the above selector expressions to give you full DOM-traversing power!



November 13th, 2006 at 11:39 am
Nice concise example that should be very handle for people new to jQuery’s syntax.
November 15th, 2006 at 3:05 am
Excellent examples. Good for learning, and good for “pwoer of jQuery” -show-offs too.
November 15th, 2006 at 6:46 am
Also a good way to learn advanced CSS selectors!
November 15th, 2006 at 10:00 am
Hey, thanks a lot for the compliments.
Can’t wait until a large enough percentage of users have migrated from IE6 to put some of those nifty CSS rules to work without having to worry about IE ruining the fun. 
Chris, won’t it be nice to actually be able to use those advanced CSS selectors in our stylesheets, now the IE7 is out the door?
November 16th, 2006 at 7:17 am
It would be lovely, Karl, but it’s never going to happen. I fear we are stuck with IE6 forever. Only 23% of web users are running XP SP2, the only platform on which IE7 may be installed. Even when Vista (where IE7 is native) goes live, it’s unlikely to move IE7 use above legacy systems running IE6 in the forseeable future. The best we can hope for is a continued stream of one-way conversions to Firefox.
November 16th, 2006 at 9:53 am
Chris, you make a good point, and I’m certainly not holding my breath. My comment did seem a little too eager, I suppose. Still, “never” and “forever,” I think, are as overly pessimistic as my comment was overly optimistic. After all, (almost) nobody bothers to support IE4 anymore, and fewer and fewer are supporting IE5.0.
So, we sit and wait and hope and pray that people switch to Firefox or Opera — or at least IE7. In the meantime, conditional comments are my new best friend.
December 5th, 2006 at 2:24 am
[…] Learning jQuery » Blog Archive » How to Get Anything You Want - part 1 (tags: javascript jquery) […]
December 10th, 2006 at 8:01 pm
How would you accomplish this with hover instead of click?
December 10th, 2006 at 11:36 pm
William, to target any of these selectors on hover, you would use the
.hover()method. For example:$("hovered_element").hover(function() {// Stuff to do when the mouse enters the element;
}, function() {
// Stuff to do when the mouse leaves the element;
});
December 11th, 2006 at 7:05 am
Thank you! That little bit of information has really helped me move forward in learning jQuery. Great site! Please, keep up the posting.
January 10th, 2007 at 7:16 pm
Very nice! I was ripping my hair out trying to get the id of the first div with a specific class. Your example of $(’li:lt(3)’) did the trick. I simply used the following:
var firstdiv = $(’div.myclass:eq(0)’).id();
Thank you!
January 12th, 2007 at 10:19 pm
Hey DePaul, Glad you got it working. By the way, if you plan to switch to jQuery 1.1 when it’s released, you’ll need to use
.attr('id')instead of.id(), unless you use the compatibility plugin.January 31st, 2007 at 6:18 pm
Nice post, but …
This part of code :
$('#show-alert').click(function() {
$('<div class="quick-alert">Alert! Watch me before it\'s too late!</div>') .insertAfter( $(this) );
}
should be AVOIDED as is. Inserting HTML code like this is really ugly, it’s a lot better to use the DOM methods :
$('#show-alert').click(function() {
var oDIV = document.createElement('div');
oDiv.className = 'quick-alert';
oText = document.createTextNode("Alert ! Watch me before it's too late !");
$(oDiv).append(oText);
$(oDiv).insertAfter(this);
}
Or, with the DOMCreate plugin for jQuery :
$('#show-alert').click(function() {
var oDiv = jQuery.create('div', {'class':'quick-alert'}, ["Alert ! Watch me before it's too late !"]});
$(this).after(oDiv);
}
August 5th, 2007 at 2:29 pm
Regex selector please
August 15th, 2007 at 6:24 am
What’s the code for selecting the external link?
August 15th, 2007 at 8:50 am
Stefan, my powers of influence are very limited when it comes to feature requests. You might want to check out the jQuery Development Google Group for previous threads regarding regular expression selectors.
Wolfwood, if none of your internal links use a fully qualified URL (one beginning with “http”), you could do it this way:
$('a[@href^=http]'). If you’re not sure about how thehrefis written for every internal link, you could add a.not()method, like so:$('a[@href^=http]').not('[@href*=mysite.com]'), where “mysite.com” is your domain.October 10th, 2007 at 10:59 am
I am wondering about this. How do I get the value of the attribute here on the main . I have a click event on the and I want to get the “id” to submit a URL. In this example I want to send the link “?m=delete&id=5″
I want to generate an alert when the user clicks on the button. I want to grab the “id” of the parent and the value of the with class=”title”
October 10th, 2007 at 11:04 am
Sorry, table got messed up. Here is the table cells:
October 10th, 2007 at 12:41 pm
Hi Asle,
Looks like you need to change .parent() to .parents() and then tweak the “tid” line a bit. Give this a try:
Note: I also changed “tr” to “tr:first” in case you have nested tables.
October 11th, 2007 at 9:11 am
Thanks, that solved it and gave me a better understanding of traversing!
October 11th, 2007 at 10:07 am
Refering to your answer to Stefan, I want to submit a link after checking a form. It seems with jQuery I do not have to have <a> to make a link. I have a button in my last post. I need a confirm before sending the link. Should I have the button as a link or do it this way?
So answering yes would send a link to the same page with params. But the page is not loaded when I use the “return confirm” statement.
October 23rd, 2007 at 7:10 am
[…] How to get everything you want part 1 How to get everything you want part 2 jQuery Selectors […]
November 6th, 2007 at 12:17 am
Hi Mike,
Part 2 has been out for a while.
To select all elements with a particular class unless they have a specific descendant element, you could do this:
$('.some-class:not(:has(someElement))')If you need to remove elements only based on their direct children (rather than any descendant), then you could do this:
May 28th, 2008 at 6:40 am
This is only a TEST
July 14th, 2008 at 3:48 pm
How do you access the selectors on a parent page: IE I want to send selected checkbox values, from a window opened by javascript back to a textarea element on the parent page.?
thanks
sas
August 22nd, 2008 at 5:57 am
How would I access value 1, 2 and 3 in href? Right now to make it easy I have
stored my different values in id, in name and title attribute but that’s somehow
an abuse.
[a class=”test” href=”javascript:myFunction(value1,value2,value3)”]
thx
August 23rd, 2008 at 4:10 pm
This is a test as I might use something similar on my new web site!