How to check if selected text is a link?

I have a very simple WYSIWYG editor using contenteditable. It works fine, but I want to check if the selected text is used as a link. When I use document.queryCommandState ('CreateLink'), it always returns false, even if the text is within the bounds. An example is below.

Am I doing this wrong or is there another way to check if the text is used as a link?

<script>
    function testLink () {

        // check if this is a link
        var state = document.queryCommandState('CreateLink');
        alert(state);

        // create the link
        document.execCommand ('CreateLink', false, 'http://www.example.com');
    }
</script>

<div contenteditable="true">Here is some sample text to test with.</div>
<br /><br />
<button onclick="testLink();">Test the state of the create link command</button>
+3
source share
1 answer

This is an old thread, but since I'm working on the same problem now, I want to point you to an already existing answer: check the status of execCommand createlink

, queryCommandState ( "CreateLink" ), , . rangy WYSIWYG. , Node , href , . script:

var range = rangy.getSelection().getRangeAt(0);
var container = range.commonAncestorContainer;
if (container.nodeType == 3) {container = container.parentNode;}
if(container.nodeName === "A") {alert ("Yes, it an anchor!");}
+2

All Articles