Last Updated: February 12, 2020
·
2.235K
· wojtekkruszewsk

Raise an exception if jQuery query matches no elements

 jQuery.fn.single = function() {
  if (this.length != 1) {
    throw new Error("Expected 1, got " +this.length);
  }
  return this;
};

var headers = $("h1").single(); //boom!

1 Response
Add your response