Jquery hasClass element

In jquery, can I combine the “nearest” or “Parents” () with “hasClass”, so it will give me the closest element with the given class, if it exists on the page?

var matchingDiv = $(this).closest('div').hasClass('SomeClass') if ( matchingDiv != null ) { //we found matching element now manipulate it } 

I will always have either one matching div element or none. Thanks.

+4
source share
7 answers
 var matchingDiv = $(this).closest('div.SomeClass') if ( matchingDiv.length ) { // use length to find if there was a match. // closest() will always return an object. } 

If that doesn't work, maybe post some html. Maybe there is a problem?

+5
source

try this, the closest one takes a selector:

 var matchingDiv = $(this).closest('div.SomeClass') if ( matchingDiv != null ) { //we found matching element now manipulate it } 
+1
source

Closest accepts a selector so you can do this:

  var matchingDiv = $(this).closest('div.SomeClass') 

Your next line is the problem, you should check the jQuery result as follows:

 if ( matchingDiv.length ) { //we found matching element now manipulate it } 
+1
source

If you need to check if the current item can be your ancestor, you are looking. You can use a combination of is() and closest() as follows:

 var matchingDiv = $(this).closest('.SomeClass'); matchingDiv = matchingDiv.length == 0 ? (matchingDiv.is('.SomeClass') ? matchingDiv : null) : matchingDiv if ( matchingDiv != null ) { //found matching element } 
+1
source

Are you asking if this will work or not?

On top of my head, I would say that it is because the jQuery paradigm is based on the union of jQuery functions.

0
source

doc for the nearest

 var matchingDiv = &(this).closest('.SomeClass') if ( matchingDiv != null ) { //we found matching element now manipulate it } 
0
source

The difference between closest () and parent () is that parent () can give you more than one element if your selector matches multiple. (what is it for)

0
source

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


All Articles