i'm relatively new to html and JS. I have done my research about "document.getElementsByTagName()" but didn't understand much.
I need to do a page that has 2 headings, one combobox and 1 button. When the onclick at the button is triggered the heading must change its background color depending on the option that is chosen at the combobox and decolorize with the same technique. Here is what i 've done so far:
function colorDiscolor() {
var getButton=document.getElementById('b1');
var element=document.getElementById('combo');
var optionValue=element.options[element.selectedIndex].value;
if (getButton.value=="Colorize") {
getButton.value="Decolorize";
if (optionValue=="level_1") {
//obviously wrong
document.getElementsByTagName('h1').style.backgroundColor="yellow";
}
else {
//obviously wrong
document.getElementsByTagName('h2').style.backgroundColor="yellow";
}
}
else {
getButton.value="Colorize";
if (optionValue=="level_1") {
//obviously wrong
document.getElementsByTagName('h1').style.backgroundColor="white";
}
else {
//obviously wrong
document.getElementsByTagName('h2').style.backgroundColor="white";
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Ex17</title>
<script type="text/javascript" src="Script.js"></script>
</head>
<body>
<div id="h">
<h1>This is h1</h1>
<h2>This is h2</h2>
</div>
<div>
<select id="combo">
<option value="level_1">Level 1</option>
<option value="level_2">Level 2</option>
</select>
<input type="button" id="b1" value="Colorize"
onclick="colorDiscolor()"/>
</div>
</body>
</html>
The answer will help me settle things in my mind about this method. (No JQuery) Cheers!