0

My question is similar to this:

How to add my own methods to HTMLElement object?

Since the answer is 'NO', I'm wondering if I can add a method to the class instead of the HTMLElement itself, like:

<SELECT class="sel_region">

<script>
$(function(){

  $('.sel_region').doSomething();

});
</script>

If possible, how to achieve it?

2
  • how would you invoke this function?
    – Oliver
    Jun 23, 2014 at 14:20
  • This is how I invoke it: $('.sel_region').doSomething(); Just don't know how to define it.
    – abacusit
    Jun 23, 2014 at 14:25

2 Answers 2

0

$('.sel_region') isn't a class. Assuming you're using jQuery, it's a collection of all the elements on the page that have the sel_region class. If you would like to be able to add a method to jQuery, this is the link for you:

http://api.jquery.com/jquery.fn.extend/

You could do something like:

jQuery.fn.extend({
  doSomething: function() {
    return this.each(function() {
      // Do something to the matching elements, which will be `this`
   });
});

$('.one-class').doSomething();
$('.another-class').doSomething();
1
  • @abacusit You're welcome. If you're satisfied with this answer click the tick next to it to accept it. Jun 23, 2014 at 22:00
0

You, of course, could do this. You should loop all existing htmlElement instances with current class

$(".sel_region").each(function(index, element) {
  element.prototype.yourFunction = function() { console.log("exists!"); };
});

You should call this loop on Dom load

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.