JQuery plugin authoring guidelines recommend this method:
(function ($) { $.fn.resetColor = function() { return this.each(function() { var elem = $( this ); var oldColor = elem.attr("memColor"); elem.css('background-color',oldColor); }; }); }(jQuery));
- Suppose a plugin is called on many elements.
- Get the processed jQuery element to work.
Also keep in mind that there is a difference between properties ( prop() ) and attributes ( attr() ), the first refers to properties in the JavaScript DOM HTMLElements , and in the future, HTML attributes as they are indicated in the markup. And jQuery makes this distinction also since version 1.6:
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr () method sometimes took property values ββinto account when retrieving certain attributes, which can lead to inconsistent behavior. Starting with jQuery 1.6, the .prop () method provides a way to explicitly retrieve property values, while .attr () retrieves attributes.
Demo:
(function ($) { $.fn.resetColor = function() { return this.each(function() { var elem = $( this ); var oldColor = elem.attr("memColor"); elem.css('background-color',oldColor); }); }; $('.me').resetColor(); }(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="me" memColor="Red">Lorem ipsum.</div> <div class="me" memColor="Blue">Lorem ipsum.</div>
source share