I am writing a very simple jquery imitation library, to allow for some simple DOM manipulation.
I am writing methods to allow me change color of text etc. When I wish to change a class element color I have to use a loop in each method. Ideally I would like to have a function that does that loop for me that I could then use in each method. Unfortunately, my attempt at this is not working.
Please see my code below:
function _(elem) {
this.classOrId(elem);
}
_.prototype = {
add: function(text) {
if (this.e.length >= 1) {
for (var i = 0; i < this.e.length; i++) {
this.e[i].innerHTML = this.e[i].innerHTML + text;
}
} else {
this.e.innerHTML = this.e.innerHTML + text;
}
return this;
},
replace: function(text) {
if (this.e.length >= 1) {
for (var i = 0; i < this.e.length; i++) {
this.e[i].textContent = text;
}
} else {
this.e.textContent = text;
document.body.appendChild(elem);
}
return this;
}
}
_.prototype.classOrId = function(elem) {
var classOrId = elem.charAt(0);
if (classOrId === "#") {
elem = this.sliceElement(elem);
this.e = document.getElementById(elem);
return this;
} else if (classOrId === ".") {
elem = this.sliceElement(elem)
this.e = document.getElementsByClassName(elem);
return this;
}
};
_.prototype.sliceElement = function(elem) {
var elem = elem.slice(1);
return elem;
};
As you can see there is an awful lot of repetition in this code. I tried writing the following to cut down on the repition but it didn't work. Any suggestions here would be greatly appreciated.
_.prototype.loopOverElements = function(effect) {
for (var i = 0; i < this.e.length; i++) {
return this.e[i][effect];
}
}
With the code below it does not recognise the javascript DOM methods such as innerHTML
, style
when they are passed into the function.
With the code above if I pass the effect into the loopOverElements function it shows that console.log(this.e[i][effect])
is undefined when passed into the method.