views:

78

answers:

3

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 ?

+4  A: 

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");
Nick Craver
A: 

Check the length of the returned jQuery object

if ($('h3').length != 0)) {
    $('h3').attr(...);
}
else {
    $('h2').attr(...);
}
tvanfosson
A: 

.....

if ($('#Container h3').length) {
  //some attribute
} else {
 //some attribute
};
Sarfraz