2

I am looking for a way to get all the attributes of an element that begins with "on" using jQuery or Vanilla JS. I am currently getting all attributes and then looping through them to get the ones I want using the method proposed by @primvdb on this post: Get all attributes of an element using jQuery.

My code looks like this:

/* Expanding .attr as proposed by @primvdb */
(function(old) {
  $.fn.attr = function() {
    if(arguments.length === 0) {
      if(this.length === 0) {
        return null;
      }

      var obj = {};
      $.each(this[0].attributes, function() {
        if(this.specified) {
          obj[this.name] = this.value;
        }
      });
      return obj;
    }

    return old.apply(this, arguments);
  };
})($.fn.attr);

/* And then my function */
$.fn.attrThatBeginWith = function(begins){
  var attributes = this.attr();
  var attrThatBegin = {};
  for(var attr in attributes){
    if(attr.indexOf(begins)==0){
      attrThatBegin[attr] = attributes[attr];  
    }
  }
  return attrThatBegin;
};

/* Usage */
var onAttributes = $("#MyElement").attrThatBeginWith("on");

And this works but is very "dirty". It's seems like with all the vast features of jQuery there should be a better "cleaner" way to do this. Does anybody have any suggestions?

Community
  • 1
  • 1
Dustin Poissant
  • 3,201
  • 1
  • 20
  • 32

1 Answers1

6

You can get all attributes attached to an element with element.attributes.
The native attributes object can be converted to an array and then filtered based on the given string.

A plugin that does the above would look like

$.fn.attrThatBeginWith = function(begins){
    return [].slice.call(this.get(0).attributes).filter(function(attr) {
        return attr && attr.name && attr.name.indexOf(begins) === 0
    });
};

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388