Dart:html -Manipulating elements

You can use properties to change the state of an element. Node and its subtype Element define the properties that all elements have. For example, all elements have classes, hidden, id, style, and title properties that you can use to set state. Subclasses of Element define additional properties, such as the href property of AnchorElement.

Consider this example of specifying an anchor element in HTML:

<a id=”example” href=”/another/example”>link text</a>

content_copy

This <a> tag specifies an element with an href attribute and a text node (accessible via a text property) that contains the string “link text”. To change the URL that the link goes to, you can use AnchorElement’s href property:

var anchor = querySelector(‘#example’) as AnchorElement;

anchor.href = ‘https://dart.dev’;

content_copy

Often you need to set properties on multiple elements. For example, the following code sets the hidden property of all elements that have a class of “mac”, “win”, or “linux”. Setting the hidden property to true has the same effect as adding display: none to the CSS.

<!– In HTML: –>

<p>

 <span class=”linux”>Words for Linux</span>

 <span class=”macos”>Words for Mac</span>

 <span class=”windows”>Words for Windows</span>

</p>

// In Dart:

const osList = [‘macos’, ‘windows’, ‘linux’];

final userOs = determineUserOs();

// For each possible OS…

for (final os in osList) {

 // Matches user OS?

 bool shouldShow = (os == userOs);

 // Find all elements with class=os. For example, if

 // os == ‘windows’, call querySelectorAll(‘.windows’)

 // to find all elements with the class “windows”.

 // Note that ‘.$os’ uses string interpolation.

 for (final elem in querySelectorAll(‘.$os’)) {

  elem.hidden = !shouldShow; // Show or hide.

 }

}

When the right property isn’t available or convenient, you can use Element’s attributes property. This property is a Map<String, String>, where the keys are attribute names. For a list of attribute names and their meanings, see the MDN Attributes page. Here’s an example of setting an attribute’s value:

elem.attributes[‘someAttribute’] = ‘someValue’;

Leave a comment

Your email address will not be published. Required fields are marked *