Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda