Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

128
Vistas
Uncaught TypeError: Cannot read properties of undefined (reading 'target')

I have a made a function that replaces a base64 string with the matching email address when clicking on some text.

This works, but for some reason I get this error: Uncaught TypeError: Cannot read properties of undefined (reading 'target').

JS

initEmails() {
    const emailToggles = document.querySelectorAll('.email');
    if (!emailToggles) {
        return;
    }

    emailToggles.forEach(toggle => {
        toggle.addEventListener('click', this.replaceEmail);
    });
}

replaceEmail(ev){
    const target = ev.target.closest('.email');

    if (!target.classList.contains('active')) {
        ev.preventDefault();
    }

    const email = atob(target.dataset.value);

    target.setAttribute('href', 'mailto:' + email);
    target.querySelector('.replace').innerText = email;

    target.classList.add('active');
}

HTML:

<span>
    <h5>@lang('E-mail')</h5>
    <a href="javascript:void(0);" data-value="{{ base64_encode($employee->email) }}" class="email">
        <span class="replace">Toon e-mailadres</span>
    </a>
</span>

I tried checking if .email exists before initialising the functions like this:

if (document.querySelector('.email') !== null) {
    this.initEmails();
    this.replaceEmail();
}

But the error keeps popping up in my console.

What can I do to fix it?

8 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos