awpawluczkowycz
awpawluczkowycz

Reputation: 31

Understanding Getting and Setting nodeValue

I am updating a text value and I'm not sure why the first block of code doesn't work, but the alternate block does. Can someone explain this to me? They seem equivalent.

//doesn't update

newAtomicNum = 2;
oldAtomicNum = document.getElementById("atomicNumber").firstChild.nodeValue;
oldAtomicNum = newAtomicNum;

*versus* //does update

newAtomicNum = 2;
oldAtomicNum = document.getElementById("atomicNumber");
oldAtomicNum.firstChild.nodeValue = newAtomicNum;

Upvotes: 0

Views: 67

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

They're very different indeed.

In your first example, all you're updating is the variable, oldAtomicNum. There's no enduring link between that and document.getElementById("atomicNumber").firstChild.nodeValue at all. Assignment (=) copies values, it doesn't create references.

Note that this is very different from this:

newAtomicNum = 2;
atomicNum = document.getElementById("atomicNumber").firstChild;
atomicNum.nodeValue = newAtomicNum;

...which updates the value. The reason that works is that on the second line, the value we're copying into atomicNum is an object reference. Then we use that reference on the third line, assigning to one of the object's properties.

Upvotes: 0

adeneo
adeneo

Reputation: 318182

When calling nodeValue without setting it, it returns the current nodeValue, not a reference to the property.

So an element looking like

<div id="atomicNumber">test</div>

Where you call

var oldAtomicNum = document.getElementById("atomicNumber").firstChild.nodeValue;

oldAtomicNum now contains the string test, so setting the variable to something else does not update the elements nodeValue

Upvotes: 1

Related Questions