Reputation: 121
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?
Upvotes: 1
Views: 72
Reputation: 96810
You need the prefix document.
:
document.getElementById(id).setAttribute(...);
The getElementById
method is defined on the document
object. 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:
document.getElementById()
| ^ |
| |
| |
[object] [method]
The only exception is for the window
object, 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 the var
keyword when creating a variable. For example:
x = 5;
Assume that a variable x
has not been previously defined. Since x
was not created with the var
keyword, it's put on the window
object. We can check it in the console:
>> window.x;
: 5
This can lead to sticky situations in that it can conflict with another x
variable declared in an outer scope. That's why it's always important to define with var
. There shouldn't be a reason not to.
Upvotes: 3