Skip to content

Instantly share code, notes, and snippets.

@williammalo williammalo/README.md forked from 140bytes/LICENSE.txt
Last active Oct 5, 2015

Embed
What would you like to do?
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>
@Evghenusi

This comment has been minimized.

Copy link

Evghenusi commented May 29, 2012

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

@williammalo

This comment has been minimized.

Copy link
Owner Author

williammalo commented May 29, 2012

@Evghenusi
Using a placeholder variable to return undefined? Smart!
but in your code, if you do .html(0) it will return this.innerHTML

@Evghenusi

This comment has been minimized.

Copy link

Evghenusi commented May 29, 2012

"but in your code, if you do .html(0) it will return this.innerHTML"
@williammalo, your previous code also reacted)
function(a,b){if(b=a!=undefined)this.innerHTML=a;return b?this:this.innerHTML}

@maettig

This comment has been minimized.

Copy link

maettig commented May 29, 2012

Save 6 bytes?

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

This comment has been minimized.

Copy link
Owner Author

williammalo commented May 29, 2012

@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
You can’t perform that action at this time.