I am trying to add a button inside a pointer which print a log to the console. This is just meant to be a test, so I can actually make the marker run a method, but I can’t even get it to print text.
JavaScript
x
9
1
const marker = L.marker([latitude, longitude]).addTo(map);
2
3
const button = '<br/><button type="button">Click button</button>'
4
const clickbutton = document.querySelector("#click");
5
button1.addEventListener("click", function(event) {
6
console.log('This button works!');
7
});
8
marker.bindPopup(button);
9
When I load the page, I immediately get this error:
Uncaught (in promise) TypeError: Cannot read properties of null (reading ‘addEventListener’)
The console says this error is caused by
JavaScript
1
2
1
button1.addEventListener("click", function(event) {
2
but I’m not sure why it’s null. Can anyone help me out?
Advertisement
Answer
You are creating the button incorrectly.
It will be right this way:
JavaScript
1
5
1
const button = document.createElement('button');
2
3
button.id = 'delete';
4
button.textContent = 'Delete marker';
5
In order to add a button to the page, you need to find the desired parent element and add the button as a child element:
JavaScript
1
6
1
// replace this id with what you need
2
const buttonParrentId = 'button-parrent-id';
3
4
const buttonParrent = document.getElementById(buttonParrentId);
5
buttonParrent.appendChild(button);
6
Next, you can work with the button as you need:
JavaScript
1
8
1
const marker = L.marker([latitude, longitude]).addTo(map);
2
3
button.addEventListener("click", function(event) {
4
console.log('This button works!');
5
});
6
7
marker.bindPopup(button);
8
Result code example:
JavaScript
1
19
19
1
const button = document.createElement('button');
2
3
button.id = 'delete';
4
button.textContent = 'Delete marker';
5
6
// replace this id with what you need
7
const buttonParrentId = 'button-parrent-id';
8
9
const buttonParrent = document.getElementById(buttonParrentId);
10
buttonParrent.appendChild(button);
11
12
const marker = L.marker([latitude, longitude]).addTo(map);
13
14
button.addEventListener("click", function(event) {
15
console.log('This button works!');
16
});
17
18
marker.bindPopup(button);
19