0

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.

BlueRayi
  • 11
  • 2

1 Answers1

1

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);
  });
}
BlueRayi
  • 11
  • 2