Reputation: 1928
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.
Upvotes: 2
Views: 1291
Reputation: 9066
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);
};
Upvotes: 1
Reputation: 3101
setAttribute is the property of singleElement but document.getElementsByTagName('h1') will return you an array instead of single element. Either use document.getElementsById('h1ID') or document.getElementsByTagName('h1')[0] .
More information https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttribute
Upvotes: 1
Reputation: 1492
var y = document.getElementsByTagName('h1')[i].innerHTML; The document.getElementsByTagName returns an array not a single element. So you can explicitly give an index and try.
Upvotes: 0