Find the closest node of certain type from a specific position

Hi people, I need to get the closest node of a particular type from a known position.

So let’s say I have the following nodes

image abc paragraph(1) paragraph(2)

I need to know from both paragraph which the closest abc node is in order to perform certain logic

So I was planning to loop recursively using nodeBefore method until I found the abc node, but just wondering if there is a better way.

Something like this should work.

let found  = -1
doc.nodesBetween(pos, doc.content.length, (node, pos) => {
  if (found > -1) return false
  if (isMyNode(node)) found = pos
if (found > -1) console.log("there's a node at", found)

Thanks worked like a charm!

I’m really confused by this question/answer. Isn’t the need to search backwards (“using nodeBefore”) from a given paragraph to find the “abc”?

But the nodesBetween is starting from pos (which I assume to be the initial pos we’re searching from?) and scans forwards towards doc.content.length.

But @MakarovCode is happy so I am misunderstanding something!

Hey @tslocke, I adapted this logic to work to my needs, but the general idea of the shared code helped me with the solution, on the specific case of looking backward I ended up searching from position 0 up to the node in question.

let found  = -1

  editor.view.state.doc.nodesBetween(0, pos, (node, pos) => {

    if (isMyNode(node)) {
      found = pos;
  if (found > -1) {
    return {pos: found}
  return null```

Ahh thanks - makes sense now : )