简体   繁体   中英

Usage of setAttribute method in JavaScript

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM