Skip to content

Instantly share code, notes, and snippets.

@imjoshdean
Created September 17, 2013 18:43
Show Gist options
  • Save imjoshdean/6598834 to your computer and use it in GitHub Desktop.
Save imjoshdean/6598834 to your computer and use it in GitHub Desktop.
<html>
<head>
</head>
<body>
<input id="age"/>
<div id="text">
<h1>Some Header</h1>
<p>Lorem <strong>ipsum</strong></p>
<small>Here's some smallprint</small>
Something at the end
</div>
<script>
(function() {
$ = function(id) {
this.element = document.getElementById(id);
}
var getAndSet = function(name, getter, setter) {
$.prototype[name] = function(newVal) {
if(arguments.length > 0) {
setter.apply(this.element, arguments);
}
else {
return getter.apply(this.element, arguments);
}
}
}
getAndSet("val", function() {
return this.value;
}, function(newVal) {
this.value = newVal;
})
getAndSet("html", function() {
return this.innerHTML;
}, function(newVal) {
this.innerHTML = newVal;
})
getAndSet("text", function() {
return getTextNodes(this);
}, function(newVal) {
var textNode = document.createTextNode(newVal);
this.innerHTML = '';
this.appendChild(textNode);
})
var getTextNodes = function(el) {
var childNodes = el.childNodes,
text = "";
for(var i = 0; i < childNodes.length; i++) {
var childNode = childNodes[i];
if(childNode.nodeType === 3) { // text
text += childNode.nodeValue;
}
else {
text += getTextNodes(childNode);
}
}
return text;
}
})()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment