I have a JS function that selects some elements based on the parameters
function getElement() {
var scope = document;
this.by = function(data) {
for (key in data) {
if (key == 'id') scope = scope.getElementById(data.id);
if (key == 'tag') scope = scope.getElementsByTagName(data.tag);
}
return scope;
}
}
function getEl(data) { return new getElement().by(data); }
This is called like getEl(id : 'divId', tag : 'span')
and it would select all spans in the di开发者_JAVA百科v 'divId'.
Now, I would like to make another function (inside function Element), called style that would change the CSS on all previously selected spans.
Something like
function getElement() {
var scope = document;
this.by = function(data) {
for (key in data) {
if (key == 'id') scope = scope.getElementById(data.id);
if (key == 'tag') scope = scope.getElementsByTagName(data.tag);
}
return scope;
}
this.style = function(data) {
console.log(data);
}
}
I would like to be able to do something like getEl({id : 'divId', tag : 'span').style({display : 'none'})
But this doesn't seem to work and I receive a getEl({id: "divId", tag: "span"}).style is undefined
error.
ps: this is for learning purposes only, please do not suggest jQuery or other such frameworks! :)
Kind regards!
getEl
returns the scope
variable, which is a list of DOM elements, not a reference to getElement
. You need to return this
to be able to do something like new getElement().by(data).style()
.
this.by = function(data) {
for (key in data) {
if (key == 'id') scope = scope.getElementById(data.id);
if (key == 'tag') scope = scope.getElementsByTagName(data.tag);
}
return this;
}
Then you can do getEl({id : 'divId', tag : 'span'}).style({display : 'none'})
.
To get the scope
variable, you can add something like this:
this.elements = function(){
return scope;
}
getEl({id : 'divId', tag : 'span'}).elements()
will return a list of DOM elements.
I figured it out, thanks to Rocket :)
function getElement() {
this.scope = document;
this.get = function() {
return this.scope;
}
this.by = function(data) {
for (key in data) {
if (key == 'id') this.scope = this.scope.getElementById(data.id);
if (key == 'tag') this.scope = this.scope.getElementsByTagName(data.tag);
}
return this;
}
this.style = function(data) {
console.log(typeof(this.scope));
for (key in data) {
if (this.scope.length) {
for (i = 0; i < this.scope.length; i++) {
this.scope[i].style[key] = data[key];
}
}
else {
this.scope.style[key] = data[key];
}
}
return this;
}
}
function getEl(data) { return new getElement().by(data); }
It works with:
getEl({id : "tara_content", tag : "div"}).style({display : "none"});
getEl({id : "tara_content"}).style({display : "none"});
getEl({tag : "div"}).style({display : "none"});
As Mathias Bynens noticed by()
can return an array of elements or just one element, this is why in style()
I'm checking for the length of this.scope
. (I couldn't find any way to force the type).
Thanks for the help! :)
精彩评论