In me index.html
I already have everything I want to display loaded and I want to implement a "shopping cart", however, the console shows the error that the function loadEventL()
is not a function in itself, despite the fact that in the javascript it is defined as such .
javascript code:
let allContainer = document.getElementsByClassName('MS-content');
loadEventL();
function loadEventL() {
allContainer.addEventListener('click', agregar);
}
function agregar(e) {
e.preventDefault();
console.log(e.target);
}
code in html:
<!DOCTYPE HTML>
<html lang="es">
<head>
<title>Prueba</title>
<meta charset="utf-8">
<?php require('./layout/head.php') ?>
<script src="JS/multislider.min.js"></script>
</head>
<body>
<?php require('header.php) ?>
<div class="MS-content">
<h1>Categoria 1</h1>
<div class="item">
<h2>Nombre</h2>
<img src="coming.jpg">
</div>
<div class="item">
<h2>Nombre</h2>
<img src="coming.jpg">
</div>
</div>
<div class="MS-content">
<h1>Categoria 2</h1>
<div class="item">
<h2>Nombre</h2>
<img src="coming.jpg">
</div>
<div class="item">
<h2>Nombre</h2>
<img src="coming.jpg">
</div>
<div class="item">
<h2>Nombre</h2>
<img src="coming.jpg">
</div>
</div>
<?php require('./layout/vCarrito.php') ?>
<script>
var cachebuster = Math.random(new Date().getTime() / 1000);
document.write('<scr' + 'ipt src="JS/carrito.js?cb=' + cachebuster + '" ></scr' + 'ipt>' );
</script>
</body>
</html>
As you can see, I make calls with require(...)
it since they are elements that are going to be repeated in several html files and I have them created in separate files so that if I need to make changes, they are only made in one place and also for capacity issues. of the project; some files are the style sheet, modal windows, scripts, etc.
I don't understand what is wrong so that it gives me that result, and from what I have consulted if I have well organized the html and if I have located the call to the script after everything related to html and I don't think there are any problems I am using a cachebuster for change display issues.
Maybe someone has had a similar case that can help me understand what would be wrong
Note: I use the getElementsByClassName('MS-content)
since in other files with html extension I have other ` and from what I understand it is better to use this instead of querySelectorAll()
since when it is executed it only reads the div that are already loaded in the DOM and if another site is opened that it still has that class and it doesn't add it to the NodeList that the method returns.
The flaw is that you treat
allContainer
as if it were a single object, when it is an array of objects because that is what the function returnsgetElementsByClassName()
according to its documentation .The solution is to go through it properly in a loop:
Let us know if it worked for you.