I'm a javascript beginner trying to utilize .setAttribute, array and GetElementsByTagName in a single function.
I want to make it such that the font color of h1 changes depending on what value is being input. Each value (0-9) corresponds to a specific value in the array. Then, using multiple 'if' statements (or other alternative ways), I hope to use .setAttribute to change the property of the h1 tag.
I keep either getting "Cannot read property 'setAttribute' of undefined" or "undefined is not a function", no matter how I tweak my code. Sometimes I get no console errors at all, but my code does not work.
function change() {
var y = document.getElementsByTagName('h1').innerHTML;
var color = ["Grey", "Blue", "Green", "Red", "Pink", "Yellow", "Orange", "Indigo", "Violet", "Black"];
var x = parseInt(document.getElementById('cn').value);
for (var i = 0; i < color.length; i++) {
var bgcolor = color[i];
if (x == 1) {
y.setAttribute("style", "color: blue;");
}
else if (bgcolor > 9){
alert('Please enter a number from 0 to 9');
}
}
}
<h1>Header</h1>
<p>
Input a number from 0 to 9:<br>
<input type="text" id="cn"> <br>
<input type="button" value="Change" onclick="change();">
</p>
</div>
Thank you in advance.
There is no use of innerHtml.As document.getElementsByTagName() is index based and it will return an array of all the h1 elements of the page more info on this. As here is only one h1 element,so you should write
var y = document.getElementsByTagName('h1')[0];
Also it is better to initialize the array color[] outside the function call
var y = document.getElementsByTagName('h1')[0];
var color = ["Grey", "Blue", "Green", "Red", "Pink", "Yellow", "Orange", "Indigo", "Violet", "Black"];
function change() {
var x = parseInt(document.getElementById('cn').value);
var clr='color:'+color[x];
y.setAttribute('style',clr);
};