javascriptjquerytinymcetinymce-4

How To Get HREF Of Selected Anchor Text in TinyMCE?


I have access to the selected text in TinyMCE via

var selection = parent.tinyMCE.activeEditor.selection.getContent();

but HOW do I have access to the href of selected piece of text that has already been linked? So if the text was hyperlinked to http://www.youtube.com then upon selection I can auto-populate the link box with http://www.youtube.com ... So I guess I'm looking for something like:

var href = href-of-my-selected-tinymce-text

Just for reference: I'm building a custom plug that call up and external custom dialog...

Many thanks to anybody that can give me a heads up :)


Solution

  • What you need to do is parse the returned string from getContent() call as HTML! As you've tagged your post with jQuery, I assume using jQuery for this is desired. With that said, your solution to retrieving the href value of the a element within your TincyMCE selection, do the following:

    // This value of var selectionFromTinyMCE is an example
    // of what parent.tinyMCE.activeEditor.selection.getContent(); returns to you
    var selectionFromTinyMCE = 'sit our <a href="../forum/index.php">community forum</a>! We also';
    
    // Here we take the string returned by TinyMCE, wrap it with a span tag,
    // and pass it into a jQuery. This forces jQuery to evaluate the string as HTML!
    var $jStr = $("<span>"+selectionFromTinyMCE+"</span>");
    
    // You then create new variable and store the value of the href attribute
    // of the <a> element from within your string.
    var hrefValueFromTinyMCEselection = $jStr.find("a").attr("href");
    
    // Check the console to see the result below, outputted as a string
    console.log( hrefValueFromTinyMCEselection );
    

    Here's a JSFiddle version of the code above to see it happening live (open to console to see the results logged): http://jsfiddle.net/lasha/NF9V8/