Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Determine if a matched class has a given id

Tags:

jquery

What is jQuery has id equivalent of the following statement?

$('#mydiv').hasClass('foo') 

so you could give a class name and check that it contains a supplied id.

something like:

$('.mydiv').hasId('foo') 
like image 790
Nicholas Murray Avatar asked Feb 12 '10 16:02

Nicholas Murray


People also ask

How do you find if element with specific ID exists or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

How do you check if an element has an ID?

Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.

What method's would you use to check if an element has a specific ID and if so replace it with a different ID?

Approach 2: First, we will use document. getElementById() to get the ID and store the ID into a variable. Then use JSON. stringify() method on the element (variable that store ID) and compare the element with 'null' string and then identify whether the element exists or not.

How do you check whether a class is added or not in jQuery?

The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".


2 Answers

You can bake that logic into the selector by combining multiple selectors. For instance, we could target all elements with a given id, that also have a particular class:

$("#foo.bar"); // Matches <div id="foo" class="bar"> 

This should look similar to something you'd write in CSS. Note that it won't apply to all #foo elements (though there should only be one), and it won't apply to all .bar elements (though there may be many). It will only reference elements that qualify on both attributes.

jQuery also has a great .is method that lets your determine whether an element has certain qualities. You can test a jQuery collection against a string selector, an HTML Element, or another jQuery object. In this case, we'll just check it against a string selector:

$(".bar:first").is("#foo"); // TRUE if first '.bar' in document is also '#foo' 
like image 161
Sampson Avatar answered Sep 21 '22 13:09

Sampson


I would probably use $('.mydiv').is('#foo'); That said if you know the Id why wouldnt you just apply it to the selector in the first place?

like image 25
prodigitalson Avatar answered Sep 24 '22 13:09

prodigitalson