1

I have many contenteditable div.

When I select a text by hightlighting inside a contenteditable div, I want to retrieve the contenteditable div element.

For exemple :

<div contenteditable="true">

Hello World, 

<i>this is <b>a dog</b> in the garden</i>

Thank you very much

</div>

So when I select the text "dog" by highlighting, I want to retrieve the contenteditable div element in order to know which contenteditable div I have used.

An idea ?

Edit :

I made this code, but it's not perfect :

var selection = window.getSelection();

    var node = selection.anchorNode;

    for(var i = 0; i < 50; i++)
    {
        node = node.parentNode;

        if(node.getAttribute("contenteditable") == "true")
        {
            console.log("found");
            break;  
        }
    }
totoaussi
  • 712
  • 1
  • 11
  • 27

3 Answers3

1

I think previous answers are over-complicating matters.

This is the same whether you select text or just click on an element.

You need to be able to identify the current element that you have clicked on or pressed a key on (otherwise I don't see how you can make contenteditable work sensibly).

Assuming you can do this, all you need to do is go back from CurrentElm to the parent that has the contenteditable attribute with a while loop -

while (Elm.contenteditable != true) {Elm=Elm.parent}

I confess to not providing full programming details, but I can if you need them.

The first issue is to be able to identify the CurrentElm on mouseclick or keypress.

If you can't do this, then get back to me and I'll explain - the rest then becomes easy.

Tony Duffill
  • 277
  • 1
  • 5
0

You need an event to fire after the text is highlighted. Unfortunatley, there isn't a onhighlight event so you must use something like onmouseup.

Next, you need a way to add event listeners to all your contenteditable divs. One way to use this is document.querySelectorAll(). But you may find it easer to add one event listener to the "parent" of these divs and continue on with the directions below.

The event listener for mouseup will provide an event object. See https://developer.mozilla.org/en-US/docs/Web/Events/mouseup. This object has the value currentTarget which will give you the element where the mouseup event occured, which in turn is the element where the highlighting took place.

adam-beck
  • 5,659
  • 5
  • 20
  • 34
0

This question seems to have already been asked:

javascript to get paragraph of selected text in web page

Here is another example:

http://www.codetoad.com/javascript_get_selected_text.html

Community
  • 1
  • 1
Steven Leimberg
  • 785
  • 1
  • 4
  • 18