JSFiddle - React, Tailwind, and code Playground

by sidouglas

HTML

<div>That is Node 1, <span>node2</span>, node3, and <span>node4</span></div>

CSS

span {
    background: yellow;
}

JavaScript

document.getElementsByTagName('div')[0].addEventListener('click', function () {
    var fullStr = this.innerHTML.replace(/<[^>]*>/g, ''),
        sel = window.getSelection(),
        str = sel.anchorNode.data,
        clickPos = sel.focusOffset,
        wordPosLeft = str.slice(0, clickPos + 1).search(/\S+$/),
        wordPosRight = str.slice(clickPos).search(/\s/),
        wordClicked,
        nextWordRegex,
        nextWordPosLeft,
        nextWord;
    
    if(wordPosRight < 0) {
        wordClicked = str.slice(wordPosLeft);
    } else {
        wordClicked = str.slice(wordPosLeft, wordPosRight + clickPos);
    }
    nextWordRegex = new RegExp(wordClicked);
    nextWordPosLeft = fullStr.search(nextWordRegex) + wordClicked.length;
    nextWord = fullStr.slice(nextWordPosLeft).match(/^\s*(\S*)\s*.*$/)[1];    
    console.log(window.getSelection())
    console.log('wordClicked: ' + wordClicked);
    console.log('nextWord: ' + nextWord);
});