How to know if there is a link element within the selection

后端 未结 5 1598
心在旅途
心在旅途 2021-01-06 03:46

In Javascript, I\'d like determine whether an element, say an A element, exists inside a given range/textRange. The aim is to determine if the user\'s current

5条回答
  •  佛祖请我去吃肉
    2021-01-06 03:54

    This is a bit of a pain in the bum to do cross-browser. You could use my Rangy library, which is probably overkill for just this task but does make it more straightforward and works in all major browsers. The following code assumes only one Range is selected:

    var sel = rangy.getSelection();
    if (sel.rangeCount) {
        var range = sel.getRangeAt(0);
        var links = range.getNodes([1], function(node) {
            return node.tagName.toLowerCase() == "a" && range.containsNode(node);
        });
    }
    

提交回复
热议问题