2

Trying to write a conditional with jQuery that basically states, if div.gathering does not contain a.cat-link then do the following. I have tried the following but it doesn't seem to work. Can anyone shed some light on this?

if($("div.gathering:contains('a.cat-link')")){
    $(".gathering").append("<a href='#"+data[i]["categories"][0]["category_id"]+"div' class='cat-link' id='"+data[i]["categories"][0]["category_id"]+"' rel='external'>"+data[i]["categories"][0]["category_name"]+"<br />");
}
ajax333221
  • 11,436
  • 16
  • 61
  • 95
nate8684
  • 539
  • 1
  • 9
  • 27
  • 1
    possible duplicate of [How do you check if a selector exists in jQuery?](http://stackoverflow.com/questions/299802/how-do-you-check-if-a-selector-exists-in-jquery) – JJJ Apr 10 '12 at 18:49

2 Answers2

7

How about this :

if($("div.gathering").find("a.cat-link").length == 0){
  // Conditional statement returned TRUE
}

jQuery selectors return arrays of objects that matched the given selector. This is why we use the length property.

The method that you used - $("div.gathering:contains('a.cat-link')")
would return an empty array and when testing against any object that actually exists (even if it is an empty array) JavaScript will return true.

Example -

var nateArr = []; 
if (nateArr){
  // Do the dishes...
}else{
 // Eat some waffles...
}

If you test this for yourself you will never stop washing those dishes because even though the nateArr contains zero elements it still exists therefore the conditional statement will always return true.
And your fingers will go all wrinkly

Lix
  • 47,311
  • 12
  • 103
  • 131
2

try this....

$("div.gathering:not(:contains(a.cat-link))")
    .append("<a href='#"+data[i]["categories"][0]["category_id"]+"div' class='cat-link' id='"+data[i]["categories"][0]["category_id"]+"' rel='external'>"+data[i]["categories"][0]["category_name"]+"<br />")

this will only return the div with class gathering which does not have a.cat-link....

hope this helps....

Sandeep Rajoria
  • 1,243
  • 8
  • 14
  • I like this - less code and it does the trick! +1. However we do not know if there is more code inside that conditional block, so your solution *might* not work for his situation. The more verbose methods also improve readability. [Programs should be written for people to read, and only incidentally for machines to execute.](http://stackoverflow.com/a/522895/558021) – Lix Apr 10 '12 at 19:07