BenM BenM - 9 months ago 41
Javascript Question

HTML node at caret position in contenteditable <div>

I am working on a basic Rich Text Editor (RTE) for a private site we're working on. The site requires the use of an RTE to add blog posts.

Everything is working fine, but I would like to toggle the active state of buttons in the toolbar when they have the specific style applied to them. This works fine for things like bold, italic etc., since we can use

, and so on.

The problem we have is that there is no way to detect things such as
<blockquote />
<a />

We add
elements to the RTE as follows:

// Insert a blockquote:
this._blockquote = function()
// Get the selected text:
var theText = this._getSelectedText();

// Are we replacing?
if(theText != '')
var quote = $('<blockquote />').html(theText).html();
this._cmd('inserthtml', '<blockquote>'+quote+'</blockquote>');
this._cmd('inserthtml', '<blockquote></blockquote>');

My question is, how can we detect the parent node at the caret position within a
? For example, placing my cursor inside the
node should return 'blockquote' (or something similar).

jQuery is an option.

So, given the following example:

<blockquote>Some| <b>text</b></blockquote>
^ cursor/caret position

I am looking to return
Some text
is within a blockquote).

Answer Source

So here is way you can check if to see what sort of an element you are currently in. The function works with chrome. With the recursive function we are able to return the entire array.

function returnNodeType()
   var node=null;      
   node = ((node.nodeType===1)?node:node.parentNode);      
   var nodeArray = [];
   returnarray = returnParentTag(node, nodeArray);
   return returnarray;

function returnParentTag(elem, nodeArray) {
    if( != "editor") {
        var next = returnParentTag(elem.parentNode, nodeArray);
    if(next) return next;
        return nodeArray;

A jsfiddle link can be found here :