-2

I am kinda newbie and I really want to understand why the variables we create don't just get the values inside the DOM element, but becomes the DOM element?

Here is some basic code;

var elementValues = document.getElementById("p1");
elementValues.style.color = "red";

 // I don't understand why we don't need this step in order to manipulate the DOM.
// document.getElementById.getElementById("p1") = elementValues; 

Aren't we basically saying to copy the values from DOM element with an id of p1 and paste them into elementValues?

But why the color of DOM element changes when I change the color of elementValues? From what I understand it acts like a pointer.

Liam
  • 27,717
  • 28
  • 128
  • 190
  • No, we aren’t saying that, we are saying, “get me a reference to this DOM element”, because that’s what document.getElementById does. Your chosen variable name `elementValues` simply doesn’t “match” what is actually going on. – misorude Oct 23 '18 at 09:51
  • Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Liam Oct 23 '18 at 09:56
  • Also see [Primitive value vs Reference value](https://stackoverflow.com/questions/13266616/primitive-value-vs-reference-value) – Liam Oct 23 '18 at 09:57

2 Answers2

2

In Javascript, Object variables store a reference to the objects. Hence, document.getElementById returns a reference. So when you modify the values of elementsValues, your are editing the referenced object.

Have a look on Working with Objects - Comparing Object. You could read the whole page also to have an overview.

Amessihel
  • 5,891
  • 3
  • 16
  • 40
0

Yes, it is like a pointer. By using var elementValues = document.getElementById("p1"); you are assigning a reference to the DOM element to the variable. Nothing about the element gets saved to the variable, but "where to find it".

Sv443
  • 708
  • 1
  • 7
  • 27
  • *but "where to find it"* is a bit confusing for me. The variable is a pointer to the underlying object in memory. – Liam Oct 23 '18 at 10:00