Is there an elegant way to select an item in jQuery if no other exists?

Suppose I have the following requirement: add an element eto an element with id "x", if such an element exists, otherwise add eto the body.

In DOM level 0, I can write:

var parent = document.getElementById("x") || document.body;
parent.appendChild(e);

In jQuery, the following does not work:

var parent = $("#x") || $("body");
parent.append(e);

because if no element with id xexists, the first disjunct returns an empty jquery object, with truth and not false, therefore appenddoes nothing. I can, however, write:

var parent = $("#x")[0] || $("body")[0];
parent.appendChild(e);

, jQuery HTMLElements, appendChild append. , , .

first()? , jQuery, , div id x, - . , jQuery, , . , id x ($("#x").length), , " id x, , ".

?

+5
2

jQuery DOM:

$(document.getElementById("foo") || document.body)

( jQuery), , , ( jQuery ).

first() - , $("#foo, body").first(); - , , DOM, (, @muistooshort)

+2

, , :

var parent = $('#x');
if(parent.length == 0) parent = $('body');

. , .

, , ( ):

var parent = (x = $('#header')).length ? x : $('body');
+3

All Articles