ganesh February 2016

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!

Answers


Gone Coding February 2016

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.


charlietfl February 2016

Closest looks upwards at ancestors. You are wanting to go sideways to a sibling.

Can use prev() or siblings()

$(this).prev().trigger('click');

Or

$(this).siblings('.PhotoPicker').trigger('click');


ameenulla0007 February 2016

$(".imageclick").prev().trigger("click");

you can simply use a prev selector here.. https://api.jquery.com/prev/


user2181397 February 2016

You can move up the DOM to find its parents and then search for the required child

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

JS

 function(){
         $(this).parent().find('.PhotoPicker').trigger('click');
}

jsfiddle


Hassan February 2016

You should understand the use of closest , it's job is to go upwards through its parent elements, NOT SIBLINGS, in your markup the class PhotoPicker is a sibling element, not a parent/ancestor element.

But addImage is a parent/ancestor element to imageclick. So you can access this using closest like this;

$(this).closest('.addImage')

and then you can use the find function to get the PhotoPicker element inside it like:

$(this).closest('.addImage').find('.PhotoPicker').first().trigger('click')

Post Status

Asked in February 2016
Viewed 2,082 times
Voted 13
Answered 5 times

Search




Leave an answer