Question

I want to know what is the parent element of caret in an iframe with designMode = 'on'. The reason is that want to know if currently user is typing in a p tag.

Was it helpful?

Solution

Here's a function to do this, adapted from an answer to a similar question:

function getSelectionBoundaryElement(win, isStart) {
    var range, sel, container = null;
    var doc = win.document;

    if (doc.selection) {
        // IE branch
        range = doc.selection.createRange();
        range.collapse(isStart);
        return range.parentElement();
    } else if (win.getSelection) {
        // Other browsers
        sel = win.getSelection();

        if (sel.rangeCount > 0) {
            range = sel.getRangeAt(0);
            container = range[isStart ? "startContainer" : "endContainer"];

            // Check if the container is a text node and return its parent if so
            if (container.nodeType === 3) {
                container = container.parentNode;
            }
        }
    }
    return container;
}

Example use:

var iframe = document.getElementById("your_iframe_id");
var caretElement = getSelectionBoundaryElement(iframe.contentWindow, true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top