Usually, when I'm selecting an element with jQuery, I would prefer it give me an error if it doesn't find matching element.
For example, I just had a bug where this failed because I changed the class of a ul
element:
$('ul.some-list').append(listItem)
Is there a convenient method for ensuring that my jQuery call matched an element?
You could make a plugin to use to ensure that the jQuery object is not empty:
$.fn.ensure = function() {
if (this.length === 0) throw "Empty jQuery result."
return this;
}
Usage:
$('ul.some-list').ensure().append(listItem);
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