JQuery Select 2 Divs Up

I'm a little confused about how to choose the parent element correctly, i.e. 2 DIVs.

In other words, my HTML looks like this:

 <div>Folder</div>
 <div class="file_info">
   <a href="test.jpg">Test File</a>
 </div>

Here is my current jQuery: $("a[href$='.jpg']").addClass("Image");

However, I do not want to add the class to <a>, instead I want to add the class to the “folder” 2 DIV above.

What is the best way to do this?

Thanks!

+3
source share
3 answers

This will work:

$("a[href$='.jpg']").parent().prev().addClass("Image");

First, it goes to the parent element of the selected element, and then to the closest relative to this element, thereby reaching the desired element div.

parent prev .

+4

jQuery, , - :

$("a").parent().parent();

, - . - , . a div .

$("a").parents("div:eq(1)");

, . , . , , : div:eq(1).

, div, div, 2 . , 2 , - .

, " 2", div, (:eq) 1, , JavaScript , 0, - 1 ..

$("a").parents("div").get(1);

, , .get. , .parents div. jQuery, div ( div).

.get , , . div, 1 , .parents.

, , , HTMLDivElement, jQuery. , jQuery HTMLDivElement, $().

+4
$("a[href$='.jpg']").parent().parent().addClass('Image');
+1
source

Source: https://habr.com/ru/post/1715589/


All Articles