Reputation: 953
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
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,
siblings()
method : $('#child').siblings('img').addClass('hidden');
$('#child + img').addClass('hidden');
Upvotes: 3