There is no element taken by querySelector

1

When I execute the following code, it does not call textContent because it tells me that 'myTitle' does not exist.

var miTitulo=document.querySelector("h1");
var miBoton=document.querySelector("button");
console.log(miTitulo);
function Bienvenida() {
	var miNombre= prompt('ingrese su nombre');
	localStorage.setItem('nombre', miNombre);
	miTitulo.textContent='Bienvenido '+miNombre;
}
window.addEventListener('load',Bienvenida,false);
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="PruebaEditable.js"></script>
</head>
<body style="background: gray">
	<h1>Bienvenido a mi pagina, </h1>
	<button>Cambiar usuario</button>
</body>
</html>
    
asked by Frnk 16.06.2018 в 09:09
source

1 answer

1

The problem is that you are supplying a non-existent parameter to .queryselector() . It is advisable that you always point to the id or class of the element when you use queryselector() .

Your code works if for example we add id to each HTML element and use it as a reference for myTitle and myBoton So:

var miTitulo=document.querySelector("#titulo");
var miBoton=document.querySelector("#cambiar");
console.log(miTitulo);
function Bienvenida() {
	var miNombre= prompt('ingrese su nombre');
	localStorage.setItem('nombre', miNombre);
	miTitulo.textContent='Bienvenido '+miNombre;
}
window.addEventListener('load',Bienvenida,false);
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="PruebaEditable.js"></script>
</head>
<body style="background: gray">
	<h1 id="titulo">Bienvenido a mi pagina, </h1>
	<button "cambiar">Cambiar usuario</button>
</body>
</html>

You can check for more information: valid examples of parameters used in queryselector ()

I hope it helps. Greetings!

    
answered by 16.06.2018 / 12:21
source