I have a javascript function but if I use it, it doesn’t work. If I use the same code without the function on my html it does work.
<script type="text/javascript">
function jon(str) {
id = 'j'+str;
getElementById(id).setAttribute('class', '');
}
function jover(str) {
id = 'j'+str;
getElementById(id).setAttribute('class', 'hide');
}
</script>
<form id="lijst" action="" method="POST" onSubmit="return formOK();">
<table>
<tr onMouseOver="getElementById('jtitle').setAttribute('class', '');" onMouseOut="getElementById('jtitle').setAttribute('class', 'hide');">
<th>* Title</th>
<td><input type="text" name="title" /></td>
<td id="jtitle" class="hide">Vul een film of serie titel in.</td>
</tr>
<tr onMouseOver="jon('type');" onMouseOut="jover('type');">
<th>* Type</th>
<td><select name="type"><option value="film">Film</option><option value="serie">Serie</option></select></td>
<td id="jtype" class="hide"></td>
</tr>
The title does work, but the type doesn’t work.
The console says the getElementById() isn’t defined. I tried to put var id = '' for the functions but that doesn’t work.
So how can I fix that?
You need the prefix
document.:The
getElementByIdmethod is defined on thedocumentobject. In order to call a method on any object you need to use the object on which it is defined, followed by a dot.and the method name. For example:The only exception is for the
windowobject, where that is not required when you define a function or variable on it; you can use it as if it were free-standing. But in actuality all global variables in particular are on the window object. This can be caused by accidentally omitting thevarkeyword when creating a variable. For example:Assume that a variable
xhas not been previously defined. Sincexwas not created with thevarkeyword, it’s put on thewindowobject. We can check it in the console:This can lead to sticky situations in that it can conflict with another
xvariable declared in an outer scope. That’s why it’s always important to define withvar. There shouldn’t be a reason not to.