2

My HTMl's source code is as follows:

<!doctype html>
<html lang="en">
    <head>
        <title>查找内部HTML并修改对应元素的内容</title>
        <meta charset = "utf-8">
        
    </head>
    <body>
        <p id="zxj">hello</p>
        <script src="innerhtml.js"></script>

    </body>
</html>

My javascript's resource code as follows:

var name = document.getElementById("zxj");
name.innerHTML = "test";
console.log(name.innerHTML)

When I run the above code, I get undefined from the console.So I checked my variable name and found the problem。The variable named name is a const name:never.I found that the name variable I declared is a constant. That's why I get an undefined when I access its innerHTML property. When I changed the variable name to names, the console output the correct result.

var names = document.getElementById("zxj");
names.innerHTML = "test";
console.log(names.innerHTML)

At this time, the variable of names becomes an element object, so I can modify its corresponding innerHTML value.

Why can't the variable name be set to name? Why does the value assigned to it by getElementById become a constant after the variable name is set to name? Can anyone tell me why? I am very confused! ! !

  • 2
    Probably due to the collision with https://developer.mozilla.org/en-US/docs/Web/API/Window/name – CBroe Nov 19 '20 at 13:49
  • 2
    You can't use `name` as the name of a global variable on browsers. It conflicts with the built-in `name` which is a property of the `window` object (and thus a global). This is one of the many good reasons not to use global variables at all. Instead, use modules (`script type="module"`), using a bundler if you have to support older environments that don't support them. – T.J. Crowder Nov 19 '20 at 13:50

0 Answers0