Search for "position" in the DOM for reference

I have a page with a series of links with the class "myLinkClass". These links can be in one of two DOM structures:

<div class="divClassA"> <a class="myLinkClass" ... </div> 

or

 <div class="divClassB"> <a class="myLinkClass" ... </div> 

I am attaching a click event for class references to an event handler using jQuery:

 $(document).ready(function () { $('.myLinkClass').bind('click', function (event) { //... }); }); 

How do I know if a clickable link is inside divClassA or divClassB?

Note that although links are immediate children of the div in the examples above, this may not be the case. In addition, there can be an arbitrary number of both divClassA and divClassB (not only one at a time).

+6
source share
5 answers

You can check if the clicked element has an ancestor with divClassA . If not, you can accept it in divClassB :

 $('.myLinkClass').bind('click', function (event) { if($(this).closest(".divClassA").length) { //Inside divClassA } else { //Not inside divClassA! } }); 

Here's a working example above.

+3
source

may be

 $(document).ready(function () { $('.myLinkClass').bind('click', function (event) { if($(this).parents('.divClassB').length) { //parent has divClassB } }); }); 

however, if you are trying to create different events for different "divClasses", something like this might be more appropriate:

 $(document).ready(function () { $('.divClassA .myLinkClass').bind('click', function (event) { //in divClassA }); $('.divClassB .myLinkClass').bind('click', function (event) { //in divClassB }); }); 
+1
source

you can try the following:

 var parent = $(this).parent; var parentName = parent.attr('class'); 
0
source
 $('.myLinkClass').bind('click', function (event) { if $(this).parent('div.divClassB') { ... it in a classB ... } }); 
0
source

HTML:

 <div class="divClassB"> <a class="myLinkClass">click1</a> </div> <div class="divClassA"> <a class="myLinkClass">click2</a> </div> 

JQuery

 $('.myLinkClass').bind('click', function (event) { alert($(this).parent().attr('class')); }); 

This code warning will show the class name of the parent div. If you want to use this name in state, try the following (if you have a tag larger than 2 <a> ):

 $('.myLinkClass').bind('click', function (event) { switch($(this).parent().attr('class')) { case 'divClassB': //do your stuff break; case 'divClassA': //do your stuff break; } }); 
0
source

Source: https://habr.com/ru/post/902314/


All Articles