Donald Duck Donald Duck -4 years ago 70
HTML Question

Why can't I assign a Javascript object to a DOM element?

This is my code:

<input id="input_with_id" type="text" value="hello" disabled>
<script type="text/javascript">
input_with_id = {type:"checkbox", value:"bye", disabled:false}
</script>


IE 8 shows me this error message: "This object does not manage this property or this method". But if I use this code, it works like it should:

<script type="text/javascript">
var my_var = new Object();
my_var = {a:"x", b:"y", c:"z"}
</script>


The only difference between these two codes is that in I'm trying to reassign a DOM element to a Javascript object which has the same structure as a DOM element and in the other one I'm reassigning a Javascript object to another Javascript object. Why can't you treat the DOM element like a Javascript object here although normally they work similarly?

Answer Source

var my_var = new Object(); my_var = {...}; is not exactly "normal" either. You're creating a completely new object and throwing away the first one that you created with new Object.

IE8 just doesn't like you "throwing away" a DOM element.

To put it simply, you're getting an error message because you're doing it wrong.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download