Holly Johnson Holly Johnson - 1 month ago 5
Javascript Question

Delete closet image with class jquery

Need to remove the image src of the closet img with a class and set it to hidden. This is what i have tryed so far.

<img class="img-preview" src="http://www.abmuku.com/wp-content/uploads/2012/04/google-logo-small.jpg" />
<span> random stuff here </span>
<button class="delete"> Delete

</button>


$('.delete').on('click', function(){
$(this).closest('.img-preview').remove();
console.log("ha")
});


http://jsfiddle.net/tQ5vr/38/

Answer

Use .prev() instead of .closest()

$(this).prev('.img-preview').remove();

.closest()

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

.prev()

Description: Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.

to change the src and hide it you can use

$(this).prev('.img-preview').attr('src','').hide();
Comments