Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - checking existence of elements

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 ?

like image 334
sasklacz Avatar asked Feb 28 '10 12:02

sasklacz


People also ask

How do you check if an element exists or not?

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.

Does not exist jQuery?

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.

Is visible in jQuery?

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.

What does jQuery find return?

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.


1 Answers

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"); 
like image 150
Nick Craver Avatar answered Oct 13 '22 04:10

Nick Craver