Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
Initializing JavaScript class before using it later in an html file

I have the following problem. I developed a javaScript class that is being used in conjunction with a select tag. Since the javaScript class has to parse through the DOM of the page, I would rather initialize the class once the DOM finishes loading and not necessarily when the user chooses a value from the select element. I was wondering what would be the best practice to do this.

I currently have the following code in the head:

<script>
    window.addEventListener('DOMContentLoaded', (event) => {
  
      // As soon as DOM content is loaded initialize class and have class parse through DOM     
      obj = new Object();
      
    });
</script>

and the following select down in the body:

<select name="select" id="select" onChange="obj.function(this);">
    <option value="value1">Value1</option>
    <option value="value2">Value2</option>
</select>   

However, when I run this I get an uncaught reference error for obj. What would be the best practice for this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should bind select event onChange after that document is ready to use new instance.

<script>
    window.addEventListener('DOMContentLoaded', (event) => {
  
      // As soon as DOM content is loaded initialize class and have class parse through DOM     
      obj = new Object();
      sel = document.getElementById('select')
      sel.onChange = obj.function(sel)
    });
</script>

...

<select name="select" id="select">
    <option value="value1">Value1</option>
    <option value="value2">Value2</option>
</select>   

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda