Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
How to add a button to run code inside LeafletJS marker?

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.

const marker = L.marker([latitude, longitude]).addTo(map);

const button = '<br/><button type="button">Click button</button>'
const clickbutton = document.querySelector("#click");
button1.addEventListener("click", function(event) {
    console.log('This button works!');
});
marker.bindPopup(button);

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

button1.addEventListener("click", function(event) {

but I'm not sure why it's null. Can anyone help me out?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are creating the button incorrectly.

It will be right this way:

const button = document.createElement('button');

button.id = 'delete';
button.textContent = 'Delete marker';

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:

// replace this id with what you need
const buttonParrentId = 'button-parrent-id';

const buttonParrent = document.getElementById(buttonParrentId);
buttonParrent.appendChild(button);

Next, you can work with the button as you need:

const marker = L.marker([latitude, longitude]).addTo(map);

button.addEventListener("click", function(event) {
    console.log('This button works!');
});

marker.bindPopup(button);

Result code example:

const button = document.createElement('button');

button.id = 'delete';
button.textContent = 'Delete marker';

// replace this id with what you need
const buttonParrentId = 'button-parrent-id';

const buttonParrent = document.getElementById(buttonParrentId);
buttonParrent.appendChild(button);

const marker = L.marker([latitude, longitude]).addTo(map);

button.addEventListener("click", function(event) {
    console.log('This button works!');
});

marker.bindPopup(button);

More about createElement

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!