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

241
Views
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 answers
Answer question

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 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!