它返回我[object HTMLCollection]

问题描述 投票:0回答:1

我正在尝试复制登录页面,我希望当我单击按钮时它会显示您输入的名称,但它返回 [object HTMLCollection]

我希望显示您输入的名字

var nombre = document.getElementsByClassName("Nombre")

function entrar() {
  //borramos todo el contenido del html dentro del body
  document.body.innerHTML = "";

  //añadimos el nombre
  var Elemento = document.createElement("h1")
  Elemento.textContent = "bienvenido " + nombre;
  document.body.appendChild(Elemento)
}
.contenedor {
  display: flex;
  justify-content: center;
  align-items: center;
}

.Login {
  display: flex;
  justify-content: center;
  align-items: center;
}

.Todo {
  display: block;
  justify-content: center;
}
<div class="Todo">
  <div class="Login">
    <h2>Nombre</h2>
    <input type="text" class="Nombre" id="Name">
  </div>
  <div class="contenedor">
    <h2 class="palabra">Contraseña</h2>
    <input type="password" id="Contraseña" class="Contraseña">
  </div>

  <button type="button" onclick=e ntrar()>Entrar</button>
</div>

javascript html css button
1个回答
0
投票

首先,

getElementsByClassName()
返回一个元素的 NodeList,而不是单个元素。

其次,你需要获取元素的

value
属性。您当前正在尝试将整个 NodeList 对象写入 DOM,这就是您看到
[object HTMLCollection]
输出的原因。

这是一个纠正了上述问题的工作示例:

var nombre = document.querySelector(".Nombre")

function entrar() {
  //borramos todo el contenido del html dentro del body
  document.body.innerHTML = "";

  //añadimos el nombre
  var Elemento = document.createElement("h1")
  Elemento.textContent = "bienvenido " + nombre.value;
  document.body.appendChild(Elemento)
}
.contenedor {
  display: flex;
  justify-content: center;
  align-items: center;
}

.Login {
  display: flex;
  justify-content: center;
  align-items: center;
}

.Todo {
  display: block;
  justify-content: center;
}
<div class="Todo">
  <div class="Login">
    <h2>Nombre</h2>
    <input type="text" class="Nombre" id="Name">
  </div>
  <div class="contenedor">
    <h2 class="palabra">Contraseña</h2>
    <input type="password" id="Contraseña" class="Contraseña">
  </div>

  <button type="button" onclick="entrar()">Entrar</button>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.