Advay Ratan
Advay Ratan

Reputation: 249

Javascript one innerHTML not working, other works in code

My code currently is

var seltrack = document.getElementById('seltrack').innerHTML;
var selmodel = document.getElementById('selmodel').innerHTML;

and then later on in a loop I have:

selmodel = "Weight";
seltrack = "Best"; 

The HTML code is in a separate document with an appropriate link to the js script:

<p id='seltrack' style='display:inline;color:black;'></p>
<p id='selmodel' style='display:inline;color:black;'></p>

So for me, seltrack sets just fine, however, selmodel doesn't change. I tried checking what selmodel was after each iteration and it seemed to change the innerHTML properly, however it didn't show up on the actual webpage. I've tried looking for solutions but none of them seem to work. I can give extra information if this wasn't sufficient. Thanks for helping.

Upvotes: 0

Views: 120

Answers (1)

Andr&#233; Dion
Andr&#233; Dion

Reputation: 21728

You cannot store a reference to an element's innerHTML property and then set that property via the reference. Neither of your examples should work:

var foo = document.getElementById('foo').innerHTML; // foo is a string
foo = "foo"; // document.getElementById('foo').innerHTML hasn't changed

console.log(foo);
console.log(document.getElementById('foo').innerHTML);
<div id="foo">Test</div>

You should instead store references to the Elements:

var foo = document.getElementById('foo'); // foo is an Element
foo.innerHTML = "foo";

console.log(foo.innerHTML);
console.log(document.getElementById('foo').innerHTML);
<div id="foo">Test</div>

Upvotes: 2

Related Questions