I'm new to JS, so I apologize if it's a basic question. My code is the following:
The code is broken. Why does the following error appear in the console:
TypeError: Cannot read properties of null (reading 'style')
at fe01ce2a7fbac8fafaed7c982a04e229:208
at Array.forEach (<anonymous>)
at fe01ce2a7fbac8fafaed7c982a04e229:195
I only want that if the distance is less than 20 the button is shown, if it is the opposite the button is hidden. No matter the method, maybe there is another way to do it, or the solution to my problem.
The problem comes with the CSS. Because if I put the following no error comes out and it does show up fine on the console:
if (distance < 20) {
console.log("Distance < 20");
} else {
console.log("Distance > 20");
}
What my code does is iterate. @MaikLowrey tells me that it is a problem in the DOM because the buttons are created depending on whether they exist in the iteration. My complete code is:
JS
const positions = getLugares();
positions.then((positions) => {
positions.forEach((position) => {
//Get lat and lng
const latitud_lugar = position.location.lat;
const longitud_lugar = position.location.lng;
const id_lugar = position.id;
//Calculate distance between two points
const distance = getDistanceBetweenPoints(latitud_persona, longitud_persona, latitud_lugar, longitud_lugar);
console.log("Distancia", distance);
console.log("Id lugar", id_lugar);
// Show button with id='recoger-id_lugar' if distance is less than 20 meters and hide it if distance is greater than 20 meters
// Use DOMContentLoaded to show the button
if (distance < 20) {
document.getElementById('recoger-' + id_lugar).style.display = 'block !important';
} else {
document.getElementById('recoger-' + id_lugar).style.display = 'none !important';
}
});
}).catch((error) => {
console.log(error);
});
HTML
<a href='/recoger/{id}/{id_lugar}' id='recoger-{id}' class='btn btn-light recoger hide'>Recoger</a>
Returns all buttons, with their ID. Example:
<a href='/recoger/1/1' id='recoger-1' class='btn btn-light recoger **hide**'>Recoger</a>
CSS
.hide {
display: none !important;
}