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
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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>
@Evghenusi
Copy link

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

@williammalo
Copy link
Author

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

@Evghenusi
Copy link

"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
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