domQuery

An abstraction layer of the DOM implementation that allows us to manipulate and traverse documents in an easy and intuitive way. This library is not intended as a replacement for the DOM implementation. But in most cases you will not need to use native DOM functions.

DomNode methods

  • node.query(String selectors): Finds elements
  • node.attr(String name, [Object value]): gets or sets attributes
  • node.css(String name, [String value]): gets or sets CSS attributes
  • node.text([Object value]): gets or sets inner text
  • node.html([Object value]): gets or sets inner html
  • node.data(String name, [Object value]): gets or sets data
  • node.append(Object obj): appends an object
  • node.prepend(Object obj): prepends an object
  • node.name(): gets the node name
  • node.parent(): gets the parent element
  • node.clean(): removes all child nodes
  • node.remove(): removes the node from the document
  • node.element(): gets the native Element object

Examples

Traversing and changing documents

You can use the same function domQuery to retrieve single or multiple elements.

import 'package:domquery/utils.dart';

void main() {
  // accessing a single element
  domQuery('h1')
      ..text('Changing title')
      ..css('border', '1px solid black');
  
  // accessing multiple elements
  var paragraphs = domQuery('p');
  paragraphs.forEach((item) {
    item.html('<strong>Paragraph</strong>');
  });
  
  // appends content
  domQuery('p:last-child').append(
    ' <span style="background: yellow; ">content added to the last paragraph.</span>'
  );
}

Creating instances from a given source

// creates an instance from a string
var node = new DomNode.fromString('<root><item id="1" /><item id="2" /><item id="3" /></root>');
print(node);

// creates an instance from a document
var node = new DomNode.fromDocument(myDocument);
print(node);

// creates an instance from a DOM element
var node = new DomNode.fromElement(myElement)

Creating documents from scratch

var node = new DomNode('root', callback: (DomNode target) {
  // apends a new node with childNodes
  target.append(new DomNode('user', callback: (DomNode target) {
    target.append(new DomNode('first-name', text: 'James'));
    target.append(new DomNode('last-name', text: 'Bond'));
    target.append(new DomNode('age', text: 158));
    target.append(new DomNode('bio', html: 'My name is Bond, <em>James Bond</em>'));
  }));
  
  // appends more items
  target.append(new DomNode('item', attributes: {'id': 101, 'title': 'Item 1'}));
  target.append(new DomNode('item', attributes: {'id': 102, 'title': 'Item 2'}));
  target.append(new DomNode('item', attributes: {'id': 103, 'title': 'Item 3'}));
  
  // appends raw content
  target.append('<summary>Look at my horse, my horse is amazing</summary>');
});
print(node);

Libraries

dom
exception
utils
utils