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 4532570
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T14:02:50+00:00 2026-05-21T14:02:50+00:00

I’m running an experiment to see if I can return that absolute start and

  • 0

I’m running an experiment to see if I can return that absolute start and end points of a highlighted block of test within a contentEditable (not actually important to the test) div. I’m not building a rich text editor or anything I just want to know how it’s done! So all I want to return upon right click (not important, I’m just messing with that too) are two numbers, the absolute distance from the start of the wrapper div to the start of the selection and the absolute distance from the start of the wrapper div to the end of the selection.

I thought Mootools would make this easy but I could only get their implementation to work with forms (i.e. textarea, input etc). So I had a quick bash using Google, and it all worked fine when no tags were involved, e.g. He|llo Wor|ld (where the pipe, |, represents the highlighted range) would return [2, 9] which is correct. However, the moment I add tags to the div to allow colours / formatting these numbers do not make any sense as the range only gives position relative to text nodes and not an absolute value. Any ideas how to get this? I can only imagine it involves some form of horrendous DOM manipulation.

JS:

window.addEvent('domready', function()
    {
        document.body.addEvent('contextmenu', 
            function(e)
            {
                e.stop();
            }
        );

        if(!window.SelectionHandler)
        {
            SelectionHandler = {};
        }

        SelectionHandler.Selector = {};

        SelectionHandler.Selector.getSelected = function()
        {
            var userSelection = '';

            if(window.getSelection)
            {
                userSelection = window.getSelection();
            }
            else if(document.getSelection)
            {
                userSelection = document.getSelection();
            }
            else if(document.selection)
            {
                userSelection = document.selection.createRange();
            }

            return userSelection;
        }

        SelectionHandler.Selector.getText = function(userSelection)
        {
            var selectedText = userSelection;

            if(userSelection.text)
            {
                selectedText = userSelection.text;
            }

            return selectedText;
        }

        SelectionHandler.Selector.getRange = function(userSelection)
        {
            if(userSelection.getRangeAt && typeof(userSelection.getRangeAt) != 'undefined')
            {
                var selectedRange = userSelection.getRangeAt(0);
            }
            else
            {
                var selectedRange = document.createRange();
                selectedRange.setStart(userSelection.anchorNode, userSelection.anchorOffset);
                selectedRange.setEnd(userSelection.focusNode, userSelection.focusOffset);
            }

            return selectedRange;
        }

        $('mydiv').addEvent('mousedown', 
            function(event)
            {
                if(event.rightClick)
                {
                    var userSelection   = SelectionHandler.Selector.getSelected();
                    var selectedText    = SelectionHandler.Selector.getText(userSelection);
                    var selectedRange   = SelectionHandler.Selector.getRange(userSelection);

                    // New ranges to add identifiable nodes (must be in that order!?)
                    var endRange = document.createRange();
                    endRange.setStart(selectedRange.endContainer, selectedRange.endOffset);
                    endRange.insertNode(document.createTextNode('!~'));

                    var startRange = document.createRange();
                    startRange.setStart(selectedRange.startContainer, selectedRange.startOffset);
                    startRange.insertNode(document.createTextNode('~!'));

                    // Find the position of our new identifiable nodes (and account for their removal)
                    var div_content = $('mydiv').get('html');
                    var start       = div_content.indexOf('~!');
                    var end         = div_content.indexOf('!~') - 2;

                    // Remove our identifiable nodes (DOESN'T WORK)
                    //startRange.deleteContents();
                    //endRange.deleteContents();

                    // This does work, but obviously loses the selection
                    div_content = div_content.replace('~!', '').replace('!~', '');
                    $('mydiv').set('html', div_content);

                    console.log(start + ' vs ' + end);
                }
            }
        );
    }
);

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Edit Range Test</title>
 </head>

 <script type="text/javascript" src="mootools.js"></script>
 <script type="text/javascript" src="edit_range.js"></script>

 <style>
    #mydiv {
        width: 400px;
        height: 400px;
        border: 1px solid #a2a2a2;
        padding: 5px;
    }
 </style>

 <body>
    <h1>Edit Range Test</h1>

    <div id="mydiv" contentEditable="true"><span style="color: red;">Hello</span> World! <span style="color: red;">Hello</span> World! </div>

 </body>
</html>

So when I now select He|llo Wor|ld (where the pipe, |, again represents the highlighted range) it would return [2, 4] when I want [28, 42].

EDIT: I’ve updated the code to clarify what I am trying to do. It does most of what I wanted to test, but loses the selection and is very scruffy!

Thanks in advance!

  • 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-05-21T14:02:50+00:00Added an answer on May 21, 2026 at 2:02 pm

    First, the information you get from Range objects are about as useful as you can get: for each of the start and end boundaries of the Range you get a DOM node and an offset within that node (a character offset inside a text or comment node or a child node offset otherwise), which completely describes the boundary. What you mean by “absolute start and end points” I imagine is two character offsets within the whole editable element, but that is a slippery concept: it seems simple, but is tricky to pin down. For example, how many characters does a paragraph break count for? A <br>? An <a> element with display: block? Elements such as <script> elements that contain text but are not visible to the user? Elements hidden via display: none? Elements outside the normal document flow, such as those positioned via position: absolute? Multiple consecutive whitespace characters that are rendered as a single visible character by the browser?

    Having said all that, I have recently had a go at writing code to do this, and yes, it does involve DOM manipulation (although not that horrendous). It’s extremely rudimentary and doesn’t deal satisfactorily with any of the above issues, partly because I knocked it up quite quickly for a question on SO, and partly because in general I don’t think it’s possible to deal nicely in general with all those issues. The following answer provides functions for saving and restoring the selection as character indices within an editable element: replace innerHTML in contenteditable div

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am doing a simple coin flipping experiment for class that involves flipping a
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
Specifically, suppose I start with the string string =hello \'i am \' me And
I am currently running into a problem where an element is coming back 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.