Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Matching relative to the queried node with esquery

I want to be able to query an element that is the direct descendant of the node I am querying against, and can't figure out if it is possible - it's not in the examples, and the peg.js grammar is just impenetrable enough to foil my attempts at reading it.

For example, given this Javascript snippet:

const assignmentOne = 'foo'
const assignmentTwo = 'baz'

And thus this (abbreviated) AST:

[{
  type: 'VariableDeclaration',
  declarations: [{
    type: 'VariableDeclarator',
    id: { type: 'Identifier', name: 'assignmentOne' },
    init: { type: 'Literal', value: 'foo' }
  }],
  kind: 'const'
}, {
  type: 'VariableDeclaration',
  declarations: [{
    type: 'VariableDeclarator',
    id: { type: 'Identifier', name: 'assignmentTwo' },
    init: { type: 'Literal', value: 'baz' }
  }],
  kind: 'const'
}]

Given node as the first VariableDeclaration node, I want to be able to do something like:

esquery.query(node, '~ VariableDeclaration')

To find siblings of node, but that gives me an error and I couldn't find another way to accomplish this. Here's a minimal test case, I tried to make it a snippet but I couldn't get esparse/esprima working in the browser:

const esprima = require('esprima')
const esquery = require('esquery')

var ast = esprima.parse(`
const example1 = 'foo'
const example2 = 'bar'
`)

const node = esquery.query(ast, 'VariableDeclaration')
const sibling = esquery.query(node, '~ VariableDeclaration')

Note my actual use case is much more complicated than this, so I'm not looking for ways to accomplish this specific query - I want to be able to match siblings, descendants, etc of the node I am querying against in general.

I've tried ., $, #, and & to refer to the current node, to no avail.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!