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')
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.
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.
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.
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".
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'
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With