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?
Honestly, I don't really think this is exceedingly verbose:
var parent = $('#x');
if(parent.length == 0) parent = $('body');
And its intent is also quite clear. You could even wrap it in a function if this idiom comes up a lot.
Also, here's a ternary form that only fires each query once (though it's a trade-off on readability):
var parent = (x = $('#header')).length ? x : $('body');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With