Reputation: 73
I am trying to have the script ask the user for an HTML class name and a color name, and then sets the color of all the elements of that HTML class to the given color.
I set the html to have class = wish
and there is a li
element with class = class2
. The sytax is correct for that. I just don't know what to do for it. I have been just testing alot with the document.getElementsByClassName()
feature and it hasn't worked well for me.
/*var classask=window.prompt("which class?");
var nodes = getElementsByClassName(classask);
document.writeln(nodes);*/
var styx=window.prompt("pick a classes name so for usage");
var nodes =document.getElementsByClassName(styx);
document.write(nodes);
nodes.style.color=red;
//document.write(document.getElementsByClassName(styx));
//document.writeln(x);
//document.write(document.getElementByClass(styx));
HTMLElement.Object.className=styx;
document.writeln(styx);
//var newcolor=window.prompt("pick a new color for usage");
//var nodes=(document.getElementByClass(classname));
//HTMLElementObject.className=styx;
//nodes.style.color=newcolor;
The code basically is alot of testing done by myself, I am just not sure how to get it to work. I either get it where it doesn't do anything or it just says [object HTMLCollection]
always no matter what i put in.
Upvotes: 0
Views: 196
Reputation: 707228
document.getElementsByClassName()
returns a nodeList
. This is a list of nodes. To operate on all the nodes in the nodeList
, you must loop over the nodeList
and apply your change to each item in the nodeList
like this:
var newcolor = window.prompt("pick a new color for usage");
if (newcolor !== null) {
var nodes = document.getElementsByClassName(classname);
for (var i = 0; i < nodes.length; i++) {
nodes[i].style.color = newcolor;
}
}
FYI, you also had getElementByClass
when it should be getElementsByClassName
.
Upvotes: 1
Reputation: 943216
A NodeList doesn't have a style
property. You have to loop over the HTMLElementNodes in the NodeList (it is very much like an array) and access the style
property of each one in turn.
Upvotes: 0