tags:

views:

60

answers:

3

Is there a way in jQuery or javascript to ignore all operations if the wrapped sets size is 0 withoug using if statement.

 menu.find('a[href="#add"]'). {code that should execute only if size()>0};

I guees I would normally have to do something like this

var m = menu.find('a[href="#add"]');

if m.size()>0 { do something }

Is there a shorter way of doing this?

Edit: full code

menu.find('a[href="#add"]').attr("href","#add-metaobject")[0].innerText = "Add Object";
+5  A: 

If the selector finds 0, it doesn't matter what follows it.

$(".nonExistentElement").css("color","red"); // nothing will be red

This is the case with $.each() too

$(".nonExistentElement").each(function(){
  World.technology.push(new PerpetualMotionMachine);
  // too bad this block will never take place
});

You could use a ternary operator, but it is really just another conditional check:

$("#someEl").length ? alert("found") : alert("not found") ;
Jonathan Sampson
This is true for chained operations but arbitrary code doesn't work the same.
Joel Potter
He only showed chained examples.
Jonathan Sampson
updated code fails, as it cannot find element.
epitka
The edited code sample has an array index. The specific problem is use of `innerText` instead of `text()`.
Joel Potter
menu.find('a[href="#add"]').attr("href","#add-metaobject").text("Add Object");
Lance McNearney
+2  A: 

EDIT:

Missunderstood the original question, but on your sample code you can just chain the operations as Jonathan suggests:

menu.find('a[href="#add"]').attr("href","#add-metaobject").find(":first").text("Add Object");
Joel Potter
This is the same as `….size()`.
Gumbo
That is exactly what I don't want to do, I do not want to wrap it in bunch of ifs. I guess I need null propagation in javascript.
epitka
A: 

If you're operating on each individual object found, you could use the .each() method which will not execute if no items were found:

menu.find('a[href="#add"]').each(function() {
  // do stuff... 
});
Topher Fangio