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. For example: 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 you’ll need:

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

import {remark} from 'remark'
import find from 'unist-util-find'

remark()
  .use(() => (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: [Object] } ],
  position: {
    start: { line: 1, column: 6, offset: 5 },
    end: { line: 1, column: 16, offset: 15 }
  }
}

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