Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8148337
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T14:37:43+00:00 2026-06-06T14:37:43+00:00

I am trying to extract a single word from a content editable div at

  • 0

I am trying to extract a single word from a content editable div at the position, when the mouse is clicked. For example:

Lorem ipsum dolor sit amet, cons|ectetur adipiscing elit. Cras vestibulum gravida tincidunt. Proin justo dolor, iaculis vulputate eleifend et, facilisis eu erat.*

Using the | to represent the caret, the function should return "consectetur".

My code:

window.onload = function () {
        document.getElementById("text-editor").onclick = function () {
            var caretPos = 0, containerEl = null, sel, range;
            if (window.getSelection) {
                sel = window.getSelection();
                if (sel.rangeCount) {
                    range = sel.getRangeAt(0);
                    if (range.commonAncestorContainer.parentNode == this) {
                        caretPos = range.endOffset;
                    }
                }
            } else if (document.selection && document.selection.createRange) {
                range = document.selection.createRange();
                if (range.parentElement() == this) {
                    var tempEl = document.createElement("span");
                    this.insertBefore(tempEl, this.firstChild);
                    var tempRange = range.duplicate();
                    tempRange.moveToElementText(tempEl);
                    tempRange.setEndPoint("EndToEnd", range);
                    caretPos = tempRange.text.length;
                }
            }
            var prevSpace, nextSpace, text = this.innerText;
            
            prevSpace = text.substring(0,caretPos).lastIndexOf(" ");
            nextSpace = text.indexOf(" ", caretPos + 1);
            nextSpace == -1 ? nextSpace = text.length - 1 : false;
            prevSpace++;
            console.log([prevSpace,caretPos,nextSpace].join("|"));
            var word = text.substring(prevSpace, nextSpace);
            //Removes punctuation and whitespace.
            var patt = new RegExp("([A-Za-z0-9']*)","g");
            word = patt.exec(word)[0];
            document.getElementById("current-word").innerHTML = word;
        };
    };

A function is bound to the mouse click event of the contenteditable div, which calculates the caret position and then finds the indexes of the preceding and following space characters (or beginning or end of the string altogether) and uses substring to determine the word. There is a quick regex match to remove punctuation and whitespace and we finally end up with the correct word.

This worked fine, when there was a single text node inside the contenteditable div, but as soon as I started dropping and other assorted tags, the part of the method that calculated the caret position stopped working, always calculating it to be 0. Is there a way to calculate the caret position in HTML like it did with the text?

If not, can anyone suggest an alternate method?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T14:37:44+00:00Added an answer on June 6, 2026 at 2:37 pm

    You could use the new TextRange module of my Rangy library for this, although it’s enormous overkill just for that one feature. Here’s the code you’d need:

    var sel = rangy.getSelection();
    sel.expand("word");
    var word = sel.text();
    alert(word);
    

    Otherwise, if you can live with no support for pre-Blink Opera (up to and including version 12) and Firefox < 4, you could use Selection.modify() (WebKit, Firefox) and the expand() method of TextRange (IE). Here’s an example.

    Demo: http://jsfiddle.net/timdown/dBgHn/1/

    Code:

    function getWord() {
        var sel, word = "";
        if (window.getSelection && (sel = window.getSelection()).modify) {
            var selectedRange = sel.getRangeAt(0);
            sel.collapseToStart();
            sel.modify("move", "backward", "word");
            sel.modify("extend", "forward", "word");
            
            word = sel.toString();
            
            // Restore selection
            sel.removeAllRanges();
            sel.addRange(selectedRange);
        } else if ( (sel = document.selection) && sel.type != "Control") {
            var range = sel.createRange();
            range.collapse(true);
            range.expand("word");
            word = range.text;
        }
        alert(word);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to extract the content of a single "value" attribute in a
I'm trying to extract the following items from a C file: Comments (single and
I am trying to extract .com, .net and .org links from a single webpage
Trying to extract strings that are wrapped in double brackets. For example [[this is
im trying to extract some files from a jar-file downloaded using java-webstart. below code
I am trying to extract the facebook id from an iframe in order to
I am trying to extract the video id from a youtube url using the
I am trying to extract the page name from a complex url. This post
I am trying to extract some parts of the Video: line from below text.
I'm trying to create a Javascript bookmarklet, which would extract a numeric ID from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.