I am developing a Javascript framework that makes working with the DOM easier. Right now I have an object called ez
that has methods for working with the DOM. Here is my code:
var ez = new Object();
ez.get = function(v,type) {
switch(type) {
case 'id': this.elementData = document.getElementById(v);
break;
case 'class': this.elementData = document.getElementsByClassName(v);
break;
case 'tag': this.elementData = document.getElementsByTagName(v);
break;
case 'css': this.elementData = document.querySelectorAll(v);
}
return this; //returns itself
}
ez.content = function() {
alert(this.elementData); //returns undefined
}
Then, in another Javascript file (which comes after this one in the HTML file) I execute the following code onload:
window.onload = function() {
ez.get('test','id').content(); //"test" is the id of an element in the DOM and it does have a text node called "test" also
}
What I want is for ez.get()
to return itself (which it does seem to do) and then for it to retain its elementData
property. The issue is that the property's value is not retained after I return this, and it becomes undefined
. I'm trying to do something similar to what JQuery does, where you can chain-link method calls because each method returns the object.
UPDATE
Okay, I did shorten my code for the post but here is the full code:
var ez = new Object();
ez.get = function(v,type) {
switch(type) {
case 'id': this.elementData = document.getElementById(v);
break;
case 'class': this.elementData = document.getElementsByClassName(v);
break;
case 'tag': this.elementData = document.getElementsByTagName(v);
break;
case 'css': this.elementData = document.querySelectorAll(v);
}
return this;
}
ez.isElementSet = function(execute) {
if(this.hasOwnProperty('elementData')) {
return execute();
} else {
return null;
}
}
ez.content = function() {
return this.isElementSet(function() {
return this.elementData.innerHTML;
});
}
window.onload = function() {
alert(ez.get('test','id').content());
}
Here is the HTML:
<!DOCTYPE html>
<head>
<title>EzDom</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link rel='stylesheet' type='text/css' href='css/style.css' />
<script type='text/javascript' src='ez.js'></script>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<p id='test'>Test.</p>
</body>
</html>