0

Code:

activeCell.onclick = function()
{
    console.log(element);
    element.value = this.value;
    console.log(element.value);
    console.log(element);
};

Lets say activeCell is a span with value = "678" but element is just a simple input tag ()

<input id="calendar" value="123" />

The output:

<input id="calendar" value="123">
678
<input id="calendar" value="123">

The string 123 is replaced with 678, but input tag value remains unchanged. However the output value is changed when method setAttribute is used:

element.setAttribute("value", this.value);

I was using the element.value = XXX ever since before and it worked... What are the differences?

sitilge
  • 3,687
  • 4
  • 30
  • 56
  • Does Span element has the property named "Value"? – AmGates Oct 31 '13 at 10:10
  • Use `element.propertyName` when the property is standard and the syntax is available. – Benjamin Gruenbaum Oct 31 '13 at 10:11
  • @AmGates just an example. It is not the right style, but it is possible. Was using it on table cells. – sitilge Oct 31 '13 at 10:15
  • 1
    @MartinsEglitis The difference is attributes and properties. Understand this first: http://stackoverflow.com/questions/6003819/properties-and-attributes-in-html "...The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code...." – Nicolas Marengo Oct 31 '13 at 10:18

1 Answers1

0

As per your example "value" property is predefined property of the element type "input" but not for the element type "span". So as per your function

<input id="calendar" value="123">
    <span id="activeCell">678</span>

document.getElementById('activeCell').onclick = function(){
    element = document.getElementById('calendar');
    console.log(element);
    element.value = this.value; // Here this object doesn't have the property value hence it will be assigned with value as undefined;
    console.log(element.value);
    console.log(element);
};

"this" object referring to the Span element does not have the property `"value"` by default hence it returns undefined. It is not the case with the setAttribute method.

In setAttribute method you can assign any property with any value. The basic functionality is that it checks the property stack of that object, if it finds the property you have mentioned then it assigns the value for it. If the property is not found in the property stack then it creats the new property for that object with the name you have specified and it assigns the value for it.

so document.getElementById('activeCell').setAttribute('value',"102"); It assigns the property value with the 102.

Hope this helps you understand

AmGates
  • 2,127
  • 16
  • 29