public
Last active

Using jQuery $.extend method to change DOM attributes..

  • Download Gist
$extend_dom.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
// 1. DOUBLE BAD!!
 
$("#myLink").attr("name","srhyne");
$("#myLink").attr("href","http://stephenrhyne.com";
$("myLink").html("stephenrhyne.com");
 
// 2. IN MY OPINION STILL VERY BAD..
 
$("#mylink")
.attr("name","srhyne")
.attr("href","http://stephenrhyne.com")
.html("stephenrhyne.com")
 
// 3. NOT AS UBER JQUERY DEVELOPER COOL BUT BETTER! (You don't need $ for everything!)
var myLink = $("#myLink")[0];
myLink.name = "srhyne";
myLink.href = "http://stephenrhyne.com";
myLink.html = ("stephenrhyne.com");
 
// 4. I link using just plain DOM scripting in #3. but I hate not being able to chain.
// I like this much better..
 
 
$.fn.domExtend = function(obj){
$.extend(this[0],obj);
return this;
};
$(function(){
$("#myLink").domExtend({
name : "srhyne",
href : "http://stephenhyne.com",
innerHTML : "stephenrhyne.com"
});
});
 
// 5. Of course this is the same as going like this..
 
var myLink = $("#myLink")[0],
changes = {
name : "srhyne",
href : "http://stephenhyne.com",
innerHTML : "stephenrhyne.com"
};
$.extend(myLink,changes);
 
// 4 AND 5 ARE acceptable to me.
 
//<a href="http://test.com" name="test" id="myLink" class="thisLink">Change ME!</a>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.