Reputation: 6805
I'm a bit confused on how to properly select a parent item, that is 2 DIV's up.
In other words, my HTML looks like this:
<div>Folder</div>
<div class="file_info">
<a href="test.jpg">Test File</a>
</div>
Here's my current jQuery: $("a[href$='.jpg']").addClass("Image");
However, I don't want to add the class to the <a>
, instead, I want to add the class to the 'folder' 2 DIV's above.
What's the best way to do this?
Thanks!
Upvotes: 3
Views: 4277
Reputation: 268444
Given jQuery's robustness, there's almost always more than one way to do what you need to do - here are a few methods for selecting a grandfather element:
$("a").parent().parent();
This does exactly what it sounds like - it selects the parent of your anchor's parent. The parent is the element immediately surrounding your target element. In this case, it's a div
element both times.
$("a").parents("div:eq(1)");
In this example, notice that we're using the plural parents. This looks up all parents for the element, and then returns it as a collection. We then specify which parents we'd like to have returned in the collection by providing a specific selection: div:eq(1)
.
This says we want div
elements, but specifically those div
elements that are at position 2 in our resulting collection. By definition, position 2 can only house one element, therefore we return only one element - the grandfather element.
If you're confused by me calling this "position 2" while asking for the div
that equals (:eq
) 1
, just remember that JavaScript uses a zero-based indexing system, so the first item in a collection is at index 0, and the second is at index 1, and so on.
$("a").parents("div").get(1);
Another example, similar to the last, which uses .get
. This too calls upon the .parents
method to give us all div
elements. This returns a jQuery object full of div
elements (assuming your parent-tree is full of div
elements).
The .get
method takes an index, corresponding to the element we'd like to retrieve. In this case, we're looking for the second div
element, which again would be held at index 1 on the collection resulting from the call to .parents
.
One important thing to note is that this example, unlike those that preceded it, returns an actual HTMLDivElement
, and not a jQuery object. The difference is that you cannot call the jQuery methods off of an HTMLDivElement
unless you wrap it again in $()
.
Upvotes: 4
Reputation: 4852
This will work:
$("a[href$='.jpg']").parent().prev().addClass("Image");
First it navigates to the parent element of the selected element and then to the nearest sibling before that element, thus reaching the div
element you require.
See the documentation on parent and prev for more details.
Upvotes: 4