Retrieve parent node from selection (range) in Gecko and Webkit

試著忘記壹切 提交于 2019-12-03 07:55:44

This is the code I've used to get the "parentNode" of the text cursor:

var getSelectedNode = function() {
    var node,selection;
    if (window.getSelection) {
      selection = getSelection();
      node = selection.anchorNode;
    }
    if (!node && document.selection) {
        selection = document.selection
        var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange();
        node = range.commonAncestorContainer ? range.commonAncestorContainer :
               range.parentElement ? range.parentElement() : range.item(0);
    }
    if (node) {
      return (node.nodeName == "#text" ? node.parentNode : node);
    }
};

I tweaked my IE method to approximate yours. Tested and working IE8, FF3.6, Safari4, Chrome5. I set up a jsbin preview that you can test with.

Jason

I have found that selection can get complicated and buggy across browsers. Throw in the magic of browser document editing, and it gets worse!

I took a look at how TinyMCE implements what I am trying to do, and took the same approach to modify jHtmlArea.

Basically, a link is created with a fake href. Then, it finds that dom element by searching for links with that particular href. You can then add any desired attributes and update the href with the actual url.

The solution above by gnarf is a great example of getting a selected node, and will work for most scenarios.

Below is the code for my work around:

var url = prompt("Link URL:", "http://");

if (!url) {
    return;
}

// Create a link, with a magic temp href
this.ec("createLink", false, "#temp_url#");

// Find the link in the editor using the magic temp href
var linkNode = $(this.editor.body).find("a[href='#temp_url#']");

linkNode.attr("rel", "external");

// Apply the actual desired url
linkNode.attr("href", url);

It's a hacky workaround, but should work unless somebody makes two identical links.

this.getSelection() seems to get the same in both needed browser, so:

var link=prompt('gimme link');

//add the thing

var text=this.getSelection();

var whatYouNeed=$('a:contains("'+text+'")[href="'+link+'"');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!