Reputation: 2750
I'm trying here to get the previous "img" tag when clicking on the 3rd "i" tag :
<div>
<img src="img/image1.jpg" alt="image2"/>
<div id="image_options">
<i class="material-icons md-36">account_box</i>
<label>djbaptou</label>
<div id="left_icons">
<i class="material-icons md-36 fav">favorite_border</i>
<i class="material-icons md-36 purple">question_answer</i>
<i class="material-icons md-36 full_screen">settings_overscan</i>
</div>
</div>
</div>
Here is my jQuery code :
$(".full_screen").click(function(){
var img = $(this).parent().parent().closest("img");
modal.css("display", "block");
modalImg.attr("src", img.attr("src"));
});
But when i do a "alert(img);" it says that this is undefined
Any ideas ?
Upvotes: 2
Views: 559
Reputation: 1074028
closest
won't work, because the i
element isn't a descendant of the img
element (by definition; img
elements can't have child elements).
You could use parent().parent().prev()
in that specific case, but it's fragile; the slightest change to the markup as you revise things over time will mess it up. What I'd do is add a class to the overall div
and then use closest(".the-class").find("img")
.
Or of course, since the div with the i
elements has an id
, just $("#image_options").prev()
.
Here's an example of the class option where clicking that third i
element changes the image from your user icon to mine:
$("i.purple").click(function() {
$(this).closest(".the-class").find("img").attr("src", "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG");
});
<div class="the-class">
<img src="https://graph.facebook.com/10153295750512607/picture?type=small" alt="image2"/>
<div id="image_options">
<i class="material-icons md-36">account_box</i>
<label>djbaptou</label>
<div id="left_icons">
<i class="material-icons md-36 fav">favorite_border</i>
<i class="material-icons md-36 purple">question_answer</i>
<i class="material-icons md-36 full_screen">settings_overscan</i>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 3