简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM