unified

Learn/Recipe/Find a node

How to find a node

Contents

What is a node

A node is a single language specific unit inside a syntax tree. Such as a heading in markdown, or anchor element in HTML. In unified, nodes follow the unist specification.

Finding a node

The concept of finding a node involves tree traversal of a syntax tree.

Unified compatible utilities should be used for finding a node. Utilities are functions that work with nodes. All specifications that extend unist can use the unist utilities, but they can also have their own utilities for more specific nodes.

To start finding nodes for your input your need:

For this example we use remark and unist-util-find. We want to find the first occurrence of emphasis in our markdown.

var remark = require('remark')
var find = require('unist-util-find')

remark()
  .use(function () {
    return transformer

    function transformer(tree) {
      const node = find(tree, { type: 'emphasis' })
      console.log(node)
      
    }
  })
  .processSync('Some _emphasis_, **strongness**, _more emphasis_, and `code`.')

yields

{
  type: 'emphasis',
  children: [ { type: 'text', value: 'emphasis', position: [Position] } ],
  position: Position {
    start: { line: 1, column: 6, offset: 5 },
    end: { line: 1, column: 16, offset: 15 },
    indent: []
  }
}

Read more about unist-util-find` in its readme.