Gary Green
Gary Green

Reputation: 22395

jQuery: appendTo either elements

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.

Upvotes: 0

Views: 135

Answers (3)

Ivo van der Wijk
Ivo van der Wijk

Reputation: 16775

How about

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

Assuming at least one of them exists.

Upvotes: 1

Nealv
Nealv

Reputation: 6884

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

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630429

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

Upvotes: 4

Related Questions