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

242
Vistas
Dart - `querySelector` cannot find element

I wanted to use Dart to replace JavaScript.

But it's not an advanced project. It's just a matter of dynamically changing a few elements within a single page.

For starters, I wrote the following HTML code and Dart code to find the element based on its ID and display the text in the console.

<!-- index.html -->
<html>
    <head>
        <title>Test</title>
        <script type="text/javascript" src="index.js"></script>
    </head>
    <body>
        <p id="first-paragraph">Target.</p>
    </body>
</html>
// index.dart
import 'dart:html';

void main() {
  print(querySelector('#first-paragraph')?.innerText);
}

The following command converts the file to a JavaScript file.

dart compile js index.dart -o index.js -O0

However, when I open the HTML file, the console shows null.

The first code in Dart Pad HTML mode, which is very similar to the above code, appears to work (on Dart Pad).

Why can't my code find the element?

Thanks.

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

0

Thank you for your comments. I remembered from your comments and was able to get it to work as expected by placing the script readout at the end of the body element or using window.addEventListener. I am ashamed to say that I forgot to do something so simple.

<!-- index.html -->
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <p id="first-paragraph">Target.</p>
        <script type="text/javascript" src="index.js"></script>
    </body>
</html>

or

// index.dart
import 'dart:html';

void main() {
  window.addEventListener('DOMContentLoaded', (event) => {
    print(querySelector('#first-paragraph')?.innerText)
  });
}
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