schenker
schenker

Reputation: 953

Accessing a parent div's image element using jQuery

i'm so sure i have done this before, but somehow not getting it right this time. I have the below markup.

<div>
<p id="child">Nothing important here</p>
<img src="someimage.png">
</div> 

The challenge is, i have only the 'child' id and using that i want to add a class 'hidden' to the image tag.

I tried this,

var parent = $('#child').parent();
$(parent +' img').addClass('hidden');

But this is not working. pls help to correct my code. Thanks!

Upvotes: 1

Views: 1002

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115282

You can use find() method or set the context as the second argument in jQuery.

parent.find('img').addClass('hidden');

// or
$('img', parent).addClass('hidden');

FYI : In your code parent +' img' results [object Object] img since parent is a jQuery object so that doesn't select any element.


Other alternative ways to get the elements,

  1. Using jQuery siblings() method : $('#child').siblings('img').addClass('hidden');
  2. Using next adjuscent sibling selector : $('#child + img').addClass('hidden');

Upvotes: 3

Related Questions