views:

25

answers:

3

Is there a good way to .appendTo either one element or the either depending on if it exists in the DOM?

So for example ideally I would like to do

ideal method 1:

.appendTo($('#div1') || $('#div2'));

not so good method 2:

var div1 = $('#div1'),
    div2 = $('#div2'),
    e = div1;

if (!div1.length) e = div2;

.appendTo(e);

Of course I can't do the first option because $() always returns an object so it will evaluate to true alert($ || 'a'); will always return the jQuery object.

+4  A: 

If they're in order just use .first(), like this:

.appendTo($("#div1, #div2").first());

Whichever order they occur in the DOM in, just use .first() or .last() to select from the direction you want. Also .appendTo() just gets swapped around, it'd be better to do this:

$("#div1, #div2").first().append(element);
Nick Craver
thanks that's a good way of doing it! would `.eq()` work in the same way?
Gary Green
@Gary - Yup, they're just convenience functions, `.first()` is `.eq(0)` and `.last()` is just `.eq(-1)` behind the scenes.
Nick Craver
A: 

why not just set a class on the the divs. this way if one of the divs is present it will always work.

Nealv
In some cases both divs can be present so I don't want it appending twice
Gary Green
+1  A: 

How about

  ($("#div1").get(0) || $("#div2").get(0)).appendTo(..) 

Assuming at least one of them exists.

Ivo van der Wijk
this is good too, didn't know about `.get` thanks for this :)
Gary Green