Suppose I have the following requirement: Add the element e to the element with id "x" if such an element exists, otherwise add e to 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 x exists, the first disjunct returns the empty jquery object, with is truthy, not falsy, so the append does nothing. I can, however, write:
var parent = $("#x")[0] || $("body")[0];
parent.appendChild(e);
but this solution is somewhat clunky because indexing the jQuery object gets me back to HTMLElements, so I must use appendChild instead of append. While this works, I am wondering whether this mixing of levels is appropriate or indicative of bad design.
Might there be a way to use first()? Perhaps I could create a jQuery object that was essentially an array whose first element was the div with id x, and the second was the body. I know I can do this with the jQuery constructor form that takes an element array, but then I am back to a mixing of levels. I also know how to check for the existence of an element with id x ($("#x").length), but I cannot see how this will lead to an elegant way to phrase “the element with id x if it exists, else the body.”
Does such a formulation exist?
Instead of using jQuery to select the element, you could use it to wrap the native DOM calls:
It’s not exactly elegant (or really even using jQuery), nor a universally applicable technique, but you’ll end up with something you can append to (and incur a relatively inexpensive jQuery invocation just the once).
You won’t be able to use
first()— e.g.,$("#foo, body").first();— because the order in which it returns selected elements is based on DOM order, not selector order (thanks, @muistooshort)