jQuery の hasClass で正規表現マッチを使いたい。
jQueryのプラグイン、、ではなく関数の上書き
hasClass のコードを上書きする。
$(document).ready(function(){ $.fn.hasClass = function (e) { var t = " " + e + " ", n = 0, r = this.length; for (; r > n; n++) { if (1 === this [n].nodeType && (" " + this [n].className + " ").replace(/\W/, " ").indexOf(t) >= 0) { return!0; } else if ( (e instanceof RegExp) && 1 === this [n].nodeType && (" " + this [n].className + " ").replace(/\W/, " ").match(e) ){ return true; } return!1; } } });
これで次のようにマッチするClassを元に処理ができる
$("div").last().hasClass(/clear/) $("div").last().hasClass("clear")
正規表現は意外と大事で、class が複数だったり、スペルミスしてるバカがいたりするとコレで対応しないと面倒になってくる。
追記、上書きが気持ち悪い時は、プラグインとして関数を突っ込むとOK
$(document).ready(function(){ $.fn.matchClass = function (e) { var t = " " + e + " ", n = 0, r = this.length; for (; r > n; n++) { if ( (e instanceof RegExp) && 1 === this [n].nodeType && (" " + this [n].className + " ").replace(/\W/, " ").match(e) ){ return true; } return!1; } } });