May 5, 2009
jQuery, Selecting the Previous Element With Filtering
Recently I was looking for a solution to this problem. My HTML looked like this:
<a class="file" href="download/876243.pdf">876243.pdf</a> <a class="tagcontrol" id="876243.pdf">tag</a> <a class="tag" href="index.php?tag=test">test</a> <img class="delete" title="remove this tag" src="img/tag-del.png" />

Here is how the tags will look.
The idea being that you would click the image with the “delete” class and submit an ajax call to delete the tag for that file in a Folksonomy system. I had the hardest time trying to figure out how to select the tagcontrol link, I needed to acquire it’s ID for one of the data variables in the ajax call. The answer came from prevAll(). With only the “this” reference from the clicked image, you can find and select the most previous “a” element that has the “.tagcontrol” class.
This line allowed me to find only the most previous element that had the attribute of “a” anchor tag with a class of “tagcontrol”.
$(this).prevAll("a.tagcontrol").attr("id");
Here is the complete function:
$(".delete").live("click", function() {
var thebutton = $(this);
var todelete = $(this).prev().html();
var file = $(this).prevAll("a.tagcontrol").attr("id");
$.ajax({
type: "GET",
url: "tag.php",
data: '?file=' + file + '&delete=' + todelete,
success: function(){
thebutton.prev().remove();
thebutton.remove();
}
});
return false;
});
This came in handy for me using the search expression feature of the prevAll() function. It’s official purpose is “Find all sibling elements in front of the current element”. However that may be a little hard to understand. Hopefully my little demonstration will help you employ this feature of jQuery.
