Registration for jQuery Conference 2008 is closed.

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.

  1. list item 1 with dummy link to silly.pdf
  2. list item 2 with class=”goofy
  3. list item 3 SURPRISE!
  4. list item 4 with silly link to silly.pdf
  • $('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” attribute starting 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!

27 Responses to “How to Get Anything You Want - part 1”

  1. Dan G. Switzer, II Says:

    Nice concise example that should be very handle for people new to jQuery’s syntax.

  2. Juha Suni Says:

    Excellent examples. Good for learning, and good for “pwoer of jQuery” -show-offs too.

  3. Chris Ovenden Says:

    Also a good way to learn advanced CSS selectors!

  4. Karl Says:

    Hey, thanks a lot for the compliments.
    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? :) 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. :)

  5. Chris Ovenden Says:

    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.

  6. Karl Says:

    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.

  7. Skylog » Blog Archive » links for 2006-12-05 Says:

    […] Learning jQuery » Blog Archive » How to Get Anything You Want - part 1 (tags: javascript jquery) […]

  8. William Lawrence Says:

    How would you accomplish this with hover instead of click?

  9. Karl Says:

    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;
    });

  10. William Lawrence Says:

    Thank you! That little bit of information has really helped me move forward in learning jQuery. Great site! Please, keep up the posting.

  11. DePaul Says:

    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!

  12. Karl Says:

    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.

  13. Lidocain Says:

    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);
    }

  14. Stefan Says:

    Regex selector please :)

  15. wolfwood Says:

    What’s the code for selecting the external link?

  16. Karl Says:

    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 the href is 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.

  17. Asle Says:

    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″

    
    
    Special tan
    10-10-2007
     Delete
    

    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”

    
    $("button.negative").click(function() {
    	 var qid = $(this).parent("tr").attr("id");
    	 var tid = $(this).parent("tr"):("td.title").text();
    	 return confirm('Are you sure you want to delete "' + qid +'"!');
    	 // send the user to "?m=del&id=xx "
       })
    
  18. Asle Says:

    Sorry, table got messed up. Here is the table cells:

    
    <tr id="5">
    <td class="title">Special tan</td>
    <td>10-10-2007</td>
    <td><button type="button" class="button negative"><img src="icons/cross.png" alt=""/>
    Delete</button></td>
    </tr>
    
  19. Karl Says:

    Hi Asle,

    Looks like you need to change .parent() to .parents() and then tweak the “tid” line a bit. Give this a try:

    	 var qid = $(this).parents("tr:first").attr("id");
    	 var tid = $(this).parents("tr:first").find("td.title").text();

    Note: I also changed “tr” to “tr:first” in case you have nested tables.

  20. Asle Says:

    Thanks, that solved it and gave me a better understanding of traversing!

  21. Asle Says:

    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?

    
    $("button.negative").click(function() {
    	 var qid = $(this).parents("tr:first").attr("id");
    	 var tid = $(this).parents("tr:first").find("td.title").text();
     	return confirm('Are you sure you want to delete"' + tid +'"?');
    	 location ="?m=del&Qid="+qid;
       })
    

    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.

  22. jQuery Tips » Selectors ในแบบฉบับของ jQuery Says:

    […] How to get everything you want part 1 How to get everything you want part 2 jQuery Selectors […]

  23. Karl Says:

    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:

    $('.some-class').filter(function() {
      return !$(this).children('someElement').length;
    })
  24. Tester Says:

    This is only a TEST

  25. Scott Stewart Says:

    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

  26. Florian Says:

    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

  27. James Says:

    This is a test as I might use something similar on my new web site!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <pre> <em> <i> <li> <ol> <strike> <strong> <ul>

IMPORTANT: If you wish to post code examples, please wrap them in <code> tags. Multi-line code should be wrapped in <pre><code> </code></pre> Also, use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.