This is my html:
<div class="myFormField">
<input type="text" class="myFormField city" value="" name="city" id="city">
</div>
I'm trying the to set the following but it's not working, it's returning undefined when I test with alerts:
document.getElementsByClassName("myFormField city").value = "New York";
Any help is appreciated thanks!
It should be:
document.getElementsByClassName("myFormField city")[0].value = "New York";
Please take a look at the documentation for getElementsByClassName
:
"Returns a set of elements which have all the given class names."
getElementsByClassName
returns a set of elements, so you need to access a specific element in that set to give it a value - first element of the set being [0]
, second is [1]
etc.
document.getElementsByClassName("myFormField city")
will return array of elements
so use
document.getElementsByClassName("myFormField city")[0].value
Please note that the document.getElementsByClassName
gets the array of elements with classname given . So your code should be,
document.getElementsByClassName("myFormField city")[0].value = "New York"
你也有身份证
document.getElementById("city").value = "New York";
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.