Starlex
Starlex

Reputation: 11

What is the difference between two coding methods below?

elem = document.getElementById("demo"); 
elem.innerHTML = x;           

WHY I CAN NOY WRITE THE CODE ABOVE LIKE THIS:

elem = document.getElementById("demo").innerHTML; 
elem = x;           

Upvotes: 0

Views: 43

Answers (3)

Simp4Code
Simp4Code

Reputation: 1479

// stores reference to DOM element #demo
elem = document.getElementById("demo");

// changes #demo innerHTML to "x" -- affects the DOM
elem.innerHTML = x;




// stores #demo content as a string
elem = document.getElementById("demo").innerHTML;

// changes the string to "x" -- does not affect the DOM
elem = x;

Upvotes: 0

Ricardo A
Ricardo A

Reputation: 1815

They are not the same thing. the first one:

elem = document.getElementById("demo"); 
elem.innerHTML = x;

elem is now an object, an object that is referencing the Element with the demo ID. the next line you are swapping the current value of innerHTML to whatever is the value of x;

The second one:

elem = document.getElementById("demo").innerHTML; 
elem = x;

The elem is a string, the HTML string that is inside the demo element ID is now saved on elem. The second line replaces the string inside elem with the value of x, however the innerHTML of the demo element remains unchanged.

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35011

Understand that variable names are just pointers to data in memory

If you understand this you'll be a long way to understanding that in the top, where elem is a label for an HTMLElement, it will set the innerHTML of the element. In the bottom elem is just a string. But more than that, when you set elem to x, you are just setting a new value in the label, not changing the element.

Upvotes: 1

Related Questions