Ok so basically I need to check,whether in my menu #Container
exist any third level elements (h3
to be exact) and if yes give them some attribute. If not give this attribute to second level element (h2
) which always exists. Is :
if ($('h3')) { //some attribute } else { //some attribute };
the right method ?
There are two ways to check whether an element in the HTML document exists or not using jQuery. Approach 1: Using the length property in jQuery. If the element exists, then the length property will return the total count of the matched elements with the specified selector.
In jQuery, you don't need to be worried about checking the existence of any element. If element does not exists, jQuery will do nothing. jQuery provides length property for every element which returns 0 if element doesn't exists else length of the element.
The :visible selector in jQuery is used to select every element which is currently visible. It works upon the visible elements. The elements that are consuming space in the document are considered visible elements. The height and width of visible elements are larger than 0.
jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.
Use .length for this, it's 0/false if there aren't any matches:
if ($('h3').length) { //some attribute } else { //some attribute };
Short version, less readable:
$($('h3').length ? 'h3' : 'h2').addClass("bob");
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