Reputation: 265
I'm learning javascript and to practice traversing the DOM I have created a method that returns an array of parent elements based on the 'nodeName'. I have done this so that I could select all of a certain element (that is a parent of another) and style them or change them, etc.
Element.prototype.specificParent = function(nodeName1) {
nodeName1 = nodeName1.toUpperCase();
var x = this;
var matches = [];
var allParents = [];
while(x.parentNode !== null) {
allParents.push(x.parentNode);
x = x.parentNode;
}
for(i = 0; i < allParents.length; i++) {
if(allParents[i].nodeName === nodeName1) {
matches.push(allParents[i]);
}
}
return matches;
}
This, kind of, has my desired effect. However, to access all the elements in the returned array I would need to use something like a for loop, because I can only access the elements like this:
var parents = document.getElementById("startHere").specificParent("div"); //gets all parent div elements and returns the array
//I can then style them individually:
parents[0].style.background = "black";
parents[1].style.background = "black";
//etc, etc, etc
//or I could use a for loop to style them all:
for(i = 0; i < parents.length; i++) {
parents[i].style.background = "black";
}
What I want to do is this:
var parents = document.getElementById("startHere").specificParent("div");
parents.style.background = "black"; //changing all the elements in the array
Is there a way to change the "specificParent" method so that it allows this?
This may seem like a pointless exercise but I am learning!
Thanks
Upvotes: 2
Views: 3632
Reputation: 5612
Probably the simplest way is to use arrays API.
If you can use ES6, it would look like so:
parents.forEach(parent => parent.style.background = "black")
In ES5 slightly less clear:
parents.forEach(function(parent) { parent.style.background = "black"; })
Based on your comments you can do this:
Element.prototype.specificParent = function(nodeName1) {
nodeName1 = nodeName1.toUpperCase();
var x = this;
var matches = [];
var allParents = [];
while(x.parentNode !== null) {
allParents.push(x.parentNode);
x = x.parentNode;
}
for(i = 0; i < allParents.length; i++) {
if(allParents[i].nodeName === nodeName1) {
matches.push(allParents[i]);
}
}
function setStyle(styleKey, styleValue) {
matches.forEach(function(parent) { parent.style[styleKey]= styleValue; });
}
return {
elements : matches,
setStyle : setStyle
};
}
And use it like so:
var parents = document.getElementById("startHere").specificParent("div");
parents.setStyle("background", "black");
Upvotes: 2