Access DOM Element

Using CSS Query Selector Selector

The querySelector("query") function takes one parameter which specifies the CSS query selector to match the element. It returns the first matched element. For example:

// To search an element with the provided Id.
// It will search the whole document.
var element = querySelector("#idName");

To search all matched element use querySelectorAll("query"). It returns a List of Element object.

Setting the text of an Element

In Dart, you can simply use the Element text property, which has a getter that walks the subtree of nodes for you and extracts their text.

// HTML
<p id="RipVanWinkle"></p>

// Dart
querySelector('#RipVanWinkle').text = 'Wake up, sleepy head!';

Remember, if you assign a text to the element via text property, you are going to loose any subtree and their information. And the element will be updated with a single text node with provided text.

Access Parent Element

Use parent property of Element object:

element.parent

Access Children

Use children property to get all the children of the element. It returns a List of element (List<Element>).

element.children

To access a particular child, use index:

element.children[0]

To get the total number of child nodes, use length property of children list:

var totalChild = element.children.length;

Adding a Child node

To add a new child node, use add() method of children property of the element object. This method takes only one argument which specifies the element that will be inserted at the end.

element.children.add(newChild);