Home > OS >  What is the difference between two coding methods below?
What is the difference between two coding methods below?

Time:05-28

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

WHY I CAN NOY WRITE THE CODE ABOVE LIKE THIS:

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

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

// 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;
  • Related