Sorin Buturugeanu Sorin Buturugeanu - 1 month ago 12
Javascript Question

successive js methods

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 div '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!

Answer

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.