Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent class and trigger in jquery

I want to trigger an event of the parent class by clicking a button or image.

<li class="addImage">
<input class="PhotoPicker" type="file" accept="image/*" capture="camera" onchange="angular.element(this).scope().file_changed(this)" />
<a class='imageclick' onclick=" $(this).closest('.PhotoPicker').trigger('click');">
    <img ng-src="images/add-photo.png">
</a>

Here addImage class is repeated and when I click on imageclick class, I want to trigger photopicker of that respective list. Its working good when I use,

('.PhotoPicker').trigger('click');

Kindly help me guys!

like image 367
ganesh Avatar asked Dec 04 '25 15:12

ganesh


1 Answers

They are not ancestors/descendants of each other.

You need to go up to the LI (nearest common ancestor) using closest then search down with find:

$(this).closest('li').find('.PhotoPicker').trigger('click');

You can also shorten trigger('click') to just .click() as it does exactly the same thing behind the scenes:

$(this).closest('li').find('.PhotoPicker').click();

You could use a sibling selector, but that is not as robust to changes being made in the DOM. Safer to use a common ancestor and find. For example, if the layout is changed for styling purposes and extra DIVs are added around elements, then sibling searches will fail.

like image 148
Gone Coding Avatar answered Dec 06 '25 05:12

Gone Coding