Inserting a node at the end of a document

I’m looking for the right way to insert a node at the end of a document.

I have this, which seems to work, but is there a better way that doesn’t involve creating a selection?

   const selection = Selection.atEnd(tr.doc)

   tr = tr.insert(selection.$anchor.pos + 2, node)

That’s very fragile (won’t work for some kinds of selections, for example when there’s a leaf node like a horizontal rule at the end of the document). You can just use tr.doc.content.lengthsize to get the position at the end of the document.

Thanks, tr.insert(tr.doc.content.size, node) (note size, rather than length) does the job.

1 Like