Skip to content

how to get the node surrounding the cursor? #1351

Answered by Alex-D
philippehenri asked this question in Q&A
Discussion options

You must be logged in to vote

Try something like:

let selectedNode = document.getSelection().focusNode

while (['SPAN'].indexOf(selectedNode.nodeName) < 0) { 
     selectedNode = selectedNode.parentNode; 
}

// selectedNode contains the first parent node you want

Inspired from:

Trumbowyg/src/trumbowyg.js

Lines 1289 to 1313 in f5f921c

documentSelection = t.doc.getSelection(),
selectedRange = documentSelection.getRangeAt(0),
node = documentSelection.focusNode,
text = new XMLSerializer().serializeToString(selectedRange.cloneContents()) || selectedRange + '',
url,
title,
target,
linkDefaultTarget = t.o.linkTargets[0];
while (['A', 'DIV'].indexOf(node.nodeName) < 0) {

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by Alex-D
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants