JSFiddle - React, Tailwind, and code Playground

by userdude

HTML

<div contenteditable="true">This is an <a name="anker">anchor</a>. And this is a <a href="#">normal hyperlink</a>. Please try to select them and then press the "Unlink" button.</div>

<input type="button" id="btn" value="Unlink">

CSS

a { color:Blue; cursor:hand !important!; }
input { width:60px; margin-top:10px;}

JavaScript

$(document).ready(function() {    
    $('#btn').click(function unlink() {
        var holder,
            frag,
            range,
            child;

        if (window.getSelection && window.getSelection().getRangeAt) {
            holder = document.createElement('div');
            frag = document.createDocumentFragment();
            range = window.getSelection().getRangeAt(0);

            $(holder)
                .append(range.cloneContents())
                .find('a:not([href])')
                .attr('href', '#');

            while ((child = holder.firstChild)) {
                frag.appendChild(child);
            }
            
            range.deleteContents();
            range.insertNode(frag);
        }
        
        document.execCommand("unlink", false, false);
    });    
});