Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make jQuery throw error when it doesn't match an element

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?

like image 403
nicholaides Avatar asked Jun 25 '11 19:06

nicholaides


1 Answers

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);
like image 67
Guffa Avatar answered Sep 22 '22 12:09

Guffa