Kesong Xie
Kesong Xie

Reputation: 1396

How to get the index of the node that is currently editing within the contenteditable div

I have a contenteditable div, and inside this div, I have 3 nodes

<div id="editable" contenteditable="true"><span>dear</span>world<span>hello</span></div> 

in this case, if we use code below:

console.log(document.getElementById('editable').childNodes)

we will have something like [span, text, span]. How can I get the index of the node which is being editing. For example, if the user is editing the word dear, I should get the index "0", because it's the first node, if the user is editing the word hello, I should get the index "2"

I have a function that is able to return the actual node I'm editing, but I'm not sure would help. see the jsfiddle.

Upvotes: 0

Views: 310

Answers (2)

adeneo
adeneo

Reputation: 318212

I would wrap the text nodes in spans, so you have element nodes only, and just use jQuery's index() to get the index

$('#editable').on('keydown', function(e){
    var _node = document.getSelection().anchorNode; 
    var node  = _node.nodeType == 3 ? _node.parentNode : _node;
    var index = $(this).children().index(node);

    console.log( index ); // output index

}).contents().each(function(i, node) {
    if (node.nodeType === 3) {
        $(node).wrap('<span />');
    }
});

FIDDLE

Upvotes: 3

Ohgodwhy
Ohgodwhy

Reputation: 50787

Here's a bit simpler of a way to get what you want:

var node = null;
node = window.getSelection().getRangeAt(0).commonAncestorContainer;
node = ((node.nodeType===1)?node:node.parentNode);    

var idx = Array.prototype.indexOf.call(node.parentNode.childNodes,node);

The idx will be given correctly as you want.

Upvotes: 0

Related Questions