javascript - Add function to set of DOM elements using jQuery? -


my journey being @ least on above basic level in front end still on , stumbled upon quite big problem recently.

i can select dom element, like

var element=document.getelementbyid("elementid") 

and add function it, this

function testfunction() {     alert(this.getattribute('data-self')); } element.customfunction=testfunction; 

but there chance way of doing using jquery?

tried attr(), prop(), data() , without luck on matter. data() close 1 though, because allows me execute function using $('#my-element-id').data('customfunction')(); example, still doesn't solve problem, new property of selected buttons not accessible other way.

to sum up: simplest way add generic function (like in example) collection of dom elements in way it's accessible other property?

adding function directly dom element not considered practice variety of reasons.

i'd suggest jquery plugin method pretty easy:

jquery.fn.mymethod = function() {     // iterate items in jquery collection , apply logic want     return this.each(function() {         // `this` dom element can carry out operation here         // example, flip background color         if (this.tagname === "input") {             this.style.backgroundcolor = "red";         } else {             this.style.backgroundcolor = "blue";         }      }); }  // usage of jquery plugin method: $("#elementid").mymethod(); $(".boxes, .ovals, .containers").mymethod(); 

you can pass arguments jquery plugin method , use arguments in implementation of custom method.


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -