简体   繁体   中英

Trying to make sense of [object HTMLCollection] From JavaScript .innerHTML Right Function?

I'm a newcomer to JavaScript. I'm trying to get what I thought would be a simple "onchange" event to work with an input form element and have a JavaScript function write back the value of the input using .innerHTML.

Here is what my output looks like:

First Name *

Hello [object HTMLCollection]

How do I deal with a variable returning the message of "[object HTMLcollection]" Please be explicitIn answering, because as I said, I'm a newcomer to javascript.

Here is my code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>onchange event Testing input text</title>
<script type="text/javascript">
<!--
function write_firstname()
{
var fnid = document.getElementById("fnm");
var fn = document.getElementsByName("first_name");

fnid.innerHTML = "Hello " + fn;
}
//-->
</script>
</head>
<body>
<form>
<!---->
<label for="first">First Name *</label>
<br />
<div class="form_indent">

    <input id="first" type="text" name="first_name" onChange="write_firstname();" autofocus>
    <p id="fnm"></p>
    <br />
</div>
<!----> 
<!---->
<div class="form_indent">
    <input type="submit" value="Submit">
    &nbsp;&nbsp;&nbsp;
    <input type="reset" value="Reset">
</div>
<!---->
</form>
</body>
</html>

I know it's probably something simple. Someone please kick me in the right direction!

document.getElementsByName("first_name"); returns a collection of elements matching the selector, a nodeList .

Note the s in getElements... everytime you see that, there's a chance more than one element could match, and a nodeList is returned instead of a single DOM node.

A nodeList is an array-like object containing the elements, so you're trying to add an object to a string, and as that's not really possible, javascript runs toString() to turn the nodeList into a string, and the string representation is [object HTMLCollection]

What you could be doing instead is just passing the element to the function

<input id="first" type="text" name="first_name" onchange="write_firstname(this);" autofocus>

and then do

function write_firstname(elem) {
    var fnid = document.getElementById("fnm");

    fnid.innerHTML = "Hello " + elem.value;
}

FIDDLE

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