Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active October 5, 2015 14:27
Show Gist options
  • Save williammalo/2820652 to your computer and use it in GitHub Desktop.
Save williammalo/2820652 to your computer and use it in GitHub Desktop.
jQuery .html() clone

jQuery .html() clone

A (Hopefully) perfect clone of the jQuery .html() method

If it has an argument, it will set the innerhtml of the element to the value of the argument.

If it has no argument, it returns the innerHTML of the element.

It is also chainable! yay!

function(a,b){
return
b==a? //if a is undefined
this.innerHTML //return innerHTML
: //else
(this.innerHTML=a,this) //set innerHTML to a, then, return this (allows chaining)
}
function(a,b){return b==a?this.innerHTML:(this.innerHTML=a,this)}
{
"name": "jQueryHTML",
"description": "A clone of the jQuery .html() method",
"keywords": [
"jQuery",
"dom",
"innerHTML",
"method"
]
}
<!DOCTYPE html>
<title>Foo</title>
<i>foo</i>
<b>bar</b>
<script>
foo = document.getElementsByTagName('i')[0]
bar = document.getElementsByTagName('b')[0]
inp = document.getElementsByTagName('input')[0]
Element.prototype.html = function(a,b){return b==a?this.innerHTML:(this.innerHTML=a,this)}
foo.html("text was changed!");
bar.html("This will be overwritten because .html() is chainable!")
.html(
foo.html()
)
</script>
@maettig
Copy link

maettig commented May 29, 2012

Save 6 bytes?

function(a,b){return b!=a?(this.innerHTML=a,this):this.innerHTML}

@williammalo
Copy link
Author

@maettig
AH!
How did I not see that?
Good job :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment