HTML interop
- Dart course
- Advanced
- Lesson 51/83
- 5 min
Learn DOM access with dart:html.
dart:html
dart:html is Dart's browser DOM library. It provides HTML element selection, event listening and document manipulation. It runs only in the browser; it does not compile in a console application.
Core API: document.querySelector('#app') selects an element, element.text = 'Hello' changes text, element.onClick.listen(...) listens for clicks. dart:html is used in web applications compiled with dart2js and dart2wasm.
DOM manipulation
With dart:html you select an element and change its content. Example: final el = document.querySelector('#app'); el?.text = 'Hello';. This changes the text of the element with id app.
Event listening is similar: el?.onClick.listen((e) => print('clicked'));. When the user clicks in the browser this function runs. dart:html is built on top of dart:js_interop; in modern Dart 3 new projects prefer dart:js_interop. But dart:html is still common; you will see it in older code.
Practice Print dart:html info
Add import 'dart:html';. Define a function setupDom that calls document.querySelector('#app'). In main add print('dart:html: DOM library') and print('Selector: querySelector').
Starter code
// import the dart:html package
// define setupDom (find element with DOM selector)
void main() {
// print dart:html info
}Sample solution
import 'dart:html';
void setupDom() {
final el = document.querySelector('#app');
el?.text = 'Hello';
}
void main() {
print('dart:html: DOM library');
print('Selector: querySelector');
}Expected output
dart:html: DOM library Selector: querySelector
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the dart:html parts
| Term | Meaning |
|---|---|
dart:html |
DOM library |
document |
Document root |
querySelector |
Selector |
Element |
Node type |
2 Where does dart:html run?
- In the browser Correct answer
- In a CLI app
- On the server
- On mobile
Explanation: dart:html runs only in the browser.
3 The querySelector call
document.____('#app');
document.querySelector('#app');
Explanation: document.querySelector('#app') selects the element.