Hello folks!

I'm new to JavaScript and I'm trying to test something.

Here's the code:

function addOption()
{
var txtElem = document.getElementById('hex_value');
if (txtElem.value == "")
{
alert("Cannot add empty value!!");
txtElem.focus();
}
else
{
var selectElem = document.getElementById('select');
var color = txtElem.value;
var index = selectElem.length;
var option = new Option(color, color);

selectElem.options[index] = option;
txtElem.value = "";
txtElem.focus();
}
return;
}

Here's the HTML:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>My web page</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<style type="text/css">
body {
line-height: 2em;
}
</style>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="div" style="width: 200px; height: 200px; position: relative; border: 1px solid black; left: 1000px;"></div>
<div style="position: relative; top: -200px;">
<h4 style="color: red;">Choose your div color or add hex value to the list:</h4>
<select id="select">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="black">Black</option>
</select><br />
<label for="hex_value">add hex:</label>
<input type="text" id="hex_value" /><br />
<input type="button" value="Add" onclick="addOption()" />
<input type="button" value="Change" onclick="changeColor()" />
</div>
</body>
</html>

What I'm trying to do is let user to add option to drop down list and change div background color (function which I will wrote later). The problem is with my variables:

txtElem
selectElem

when I define them inside the functions (make them local) everything works ok. But I want to define them as global variables so I can access them from both functions. When i rewrite my script like this:

var txtElem = document.getElementById('hex_value');
var selectElem = document.getElementById('select');

function addOption()
{
if (txtElem.value == "")
{
alert("Cannot add empty value!!");
txtElem.focus();
}
else
{
var color = txtElem.value;
var index = selectElem.length;
var option = new Option(color, color);

selectElem.options[index] = option;
txtElem.value = "";
txtElem.focus();
}
return;
}

it breaks. Why?

Thanks in advance.