Is there such thing as an adjacent selector in jquery?

I am trying to use the proper selectors for this code, but I can't seem to get it to work.

<ul id="message-list">
    <li class="clearfix message success unread">
        <a href="/messages/mark_read/61/" class="message-close"></a>
                Getting Real: The Smarter, Faster, Easier Way To Build A Successful Web Application
            has been added to your profile.
        <form action="/profile/tweet/NIZNQwAACAAJ/" method="post">
            <div style="display:none">
                <input type="hidden" value="3b723be17da67c5bc54b27a98a660d53" name="csrfmiddlewaretoken">
            <input type="submit" class="button tweet-button" value="Tweet This Book">

$('.tweet-button').click(function (e) {
    var $list_item = $(this).parent('ul li.message'); < ----- ? ? ?
    var $anchor = $(this).parent('a'); // ?? <------

I am trying to get the selector for the uppermost list item with class 'message' and the anchor tag adjacent to the form.

Any ideas?

Since li.message isn't an immediate ancestor of your button, use .parents() to search up the DOM tree until you reach li.message:

var $list_item = $(this).parents('li.message');

And since the anchor is a sibling of the form parent of your input, use .siblings() after selecting the .parent() to get the anchor:

var $anchor = $(this).parent().siblings('a');

By the way,

  • The a isn't adjacent to the form, although it is one of its sibling elements.

  • Nesting an input directly in a form isn't valid HTML. jQuery will still work with it, but the validator will complain (if you care about that sort of thing).

Another way, using .closest and traversing to the anchor using .prev:

var $list_item = $(this).closest('li.message');
var $anchor = $(this).closest('form').prev().prev('.message-close');