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($ || 开发者_JAVA百科'a');
will always return the jQuery object.
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);
How about
($("#div1").get(0) || $("#div2").get(0)).appendTo(..)
Assuming at least one of them exists.
why not just set a class on the the divs. this way if one of the divs is present it will always work.
精彩评论