简体   繁体   中英

what is the difference between ways of assigning values to HTML elements via javascript?

I am using Javascript with TamperMonkey to modify a website not owned by me, just to make it a little more usable. To use a simple situation I have a page with a search box and the data I need to enter in said search box happens to be on the page that is loaded. I am taking the data on the page and entering it into the search box.

I have the following code that works:

var searchBox = document.getElementById('searchtext');
searchBox.value = document.getElementById('dataToSearch').innerText;

The following code does not work. Not the only thing that changed was where the ".value" is located.

var searchBox = document.getElementById('searchtext').value;
searchBox = document.getElementById('dataToSearch').innerText;

My question is why does the first example work when the second does not? I do not get an error, it just assigned the object type instead of the actual value.

The value property of an element is actually a getter/setter:

 console.log( Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' ) );

When you do

var searchBox = document.getElementById('searchtext').value;

you invoke the getter and the current value in the input goes into the searchBox variable as a string.

Reassigning the string variable with searchBox = document.getElementById('dataToSearch').innerText; does nothing but reassign the string variable. If you want to change the input value, you'll have to invoke the setter, and the only way to invoke the setter is to assign to the .value property:

document.getElementById('searchtext').value = document.getElementById('dataToSearch').innerText;

Reassigning a variable name, by itself, eg

someVarName = newValue

will never have any side-effects (except in the very unusual case of argument lists and the arguments object).

As a side note, keep in mind that you should almost never want to use .innerText - prefer textContent if you're retrieving text, or innerHTML if retrieving HTML markup.

@CertainPerformance's answer is correct, but you'd encounter a similar phenomenon even if it was a normal property, with no getters or setters.

For example:

 const obj1 = { value: 'foo' }; let variable1 = obj1.value; variable1 = 'bar'; console.log('obj1', obj1); // { value: 'foo' } const obj2 = { value: 'foo' }; let variable2 = obj2; variable2.value = 'bar'; console.log('obj2', obj2); // { value: 'bar' }

This is because reassigning a variable ( a = 1 ) does not change other references to that variable. Setting a property , however ( ab = 1 ), mutates the object on which the property is present.

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