简体   繁体   中英

Why isn't jQuery 'closest' working when clicking on class element

I have some JavaScript generated HTML code on my page. Multiple sections/instances of the same HTML code is being generated and populated to the page. One of the DIVs in each HTML section is hidden using a CSS Class named openrole . I need to remove the hidden attribute from the next openrole DIV and do a slideToggle() on the DIV. When clicking on one Class element I am trying to find the next element of the openrole class, but no luck so fare.

I have looked through and tested tons of alternatives, but still no luck. I am hoping someone can point me in the right directin here.

 $('#role_info').append( '<li>' + '<a href="javascript:void(0)">' + '<i class="menu-icon fa fa-file-text-o bg-yellow"></i>' + '<div class="menu-info">' + '<h4 class="control-sidebar-subheading applicantinfo">' + papplicant + plusicon + '</h4>' + '<p >' + prole + '</p>' + '</div>' + '</a>' + '<div class="col-md-12 openrole">' + '<div class="col-md-6">' + '<p class="text-left standard-text">Selskapsinformasjon</p>' + '<p id="company_address" class="text-left standard-text"><i class=" icon-padding fa fa-home"></i></p>' + '<p id="company_phone" class="text-left standard-text"><i class=" icon-padding fa fa-phone"></i></p>' + '<p id="company_email" class="text-left standard-text"><i class=" icon-padding fa fa-envelope"></i></p>' + '</div>' + '<div class="col-md-6">' + '<p class="text-left standard-text">Kontaktperson</p>' + '<p id="contact_name" class="text-left standard-text"><i class=" icon-padding fa fa-user"></i></p>' + '<p id="contact_phone" class="text-left standard-text"><i class=" icon-padding fa fa-phone"></i></p>' + '<p id="contact_email" class="text-left standard-text"><i class=" icon-padding fa fa-envelope"></i></p>' + '<div>' + '</div>' + '</li>' ) $(document).on('click', '.applicantinfo', function() { $(this).closest('.openrole').slideToggle(); }); 
 .openrole { display: none; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="role_info" class="control-sidebar-menu"> </ul> 

No error messages are generated in the console. I guess I'm just not able to figure out how to write the correct JavaScript code based on the structure of my HTML

Your code should be something like this

$(this).closest('li').find('.openrole').slideToggle();

closest check for the ancestor.

closest() traversing up through its ancestors in the DOM tree. Use parent to find element like below.

So In your case:

$(document).on('click', '.applicantinfo', function () {
   $(this).parent('li').find('.openrole').slideToggle();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM