Can not read property 'addEventListener'

5

I'm doing a basic cashier simulation exercise .

I get the following error when executing the code, I could not find the error.

  

Can not read property 'addEventListener'

I would greatly appreciate your guidance, Thanks!

JS :

class billete{
constructor(v,c){
    this.valor=v;
    this.cantidad=c;
}
}
function entregarDinero()
{
for(var bi of caja)
{
    console.log(bi);
}
}

var caja=[];
var entregado=[];
caja.push(new billete(50,3));
caja.push(new billete(20,2));
caja.push(new billete(10,2));

var dinero=210;
var div=0;
var papeles=0;

var b=document.getElementById("extraer");
b.addEventListener("click", entregarDinero);

HTML

<!DOCTYPE html>
<html>
<head>
<title>Cajero</title>
</head>
<body>
<h1>Mi primer cajero!</h1>
<p> wow! :O </p>
<img src="cajero.webp">
</br>
<script src="cajero.js"></script>
<input type="number" id="dinero">
 <input type="button" value="Extraer" id="extraer" />
</body>
</html>
    
asked by Ketchup786 04.10.2018 в 19:59
source

1 answer

3

I have tested your code and it is fully functional, the only detail you could have is where you are writing the JS; I told you that your code should have this order

INDICATIONS

  

1.- Where as you can notice first I make the HTML declaration
  2.- Then I write the JS, because if I do the logic before, then the sentence where you get the button for its id, is never going to   find why at that time it does not yet exist in the DOM tree   3.- The error Cannot read property 'addEventListener' is because when that block of code is executed, that node does not exist yet,   then the safest thing is that you have the JS first and then the HTML   declared

FUNCTIONAL CODE

<!DOCTYPE html>
<html>
<head>
<title>Cajero</title>
</head>
<body>
<h1>Mi primer cajero!</h1>
<p> wow! :O </p>
<img src="cajero.webp">
</br>
<script src="cajero.js"></script>
<input type="number" id="dinero">
 <input type="button" value="Extraer" id="extraer" />
</body>
<script>
class billete{
constructor(v,c){
    this.valor=v;
    this.cantidad=c;
}
}
function entregarDinero()
{
for(var bi of caja)
{
    console.log(bi);
}
}

var caja=[];
var entregado=[];
caja.push(new billete(50,3));
caja.push(new billete(20,2));
caja.push(new billete(10,2));

var dinero=210;
var div=0;
var papeles=0;

var b=document.getElementById("extraer");
b.addEventListener("click", entregarDinero);
</script>
</html>
    
answered by 04.10.2018 / 20:04
source