epitka
epitka

Reputation: 17657

jQuery: conditionally executing without "if"

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";

Upvotes: 2

Views: 161

Answers (3)

Sampson
Sampson

Reputation: 268424

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") ;

Upvotes: 5

Joel
Joel

Reputation: 19368

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");

Upvotes: 2

Topher Fangio
Topher Fangio

Reputation: 20677

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... 
});

Upvotes: 0

Related Questions