JSFiddle - React, Tailwind, and code Playground
by Imri Paloja
HTML
<button onclick="get_download()">Check</button><br>
<input id="download" name="download" placeholder="/path/to/file.png" type="checkbox" value="" onclick="">
CSS
html,body {
background: #212121;
color: #F9F9F9;
}
JavaScript
function getEditorSelection() {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return null;
const range = selection.getRangeAt(0);
const editor = document.getElementById("editor");
if (!editor.contains(range.commonAncestorContainer)) return null;
return { selection, range, editor };
}
function create_link() {
const sel = getEditorSelection();
if (!sel) return;
const { selection, range, editor } = sel;
// If selection is collapsed, do nothing
if (range.collapsed) return;
// If already inside <a>, unwrap it (toggle behavior)
let node = selection.anchorNode;
while (node && node !== editor) {
if (node.nodeType === 1 && node.tagName === "A") {
unwrap(node);
return;
}
node = node.parentNode;
}
// Create <a> element
const a = document.createElement("a");
// Set attributes ONLY if values exist
setAttr(a, "href", document.getElementById("href").value);
setAttr(a, "hreflang", document.getElementById("hreflang").value);
setAttr(a, "media", document.getElementById("media").value);
setAttr(a, "referrerpolicy", document.getElementById("referrerpolicy").value);
setAttr(a, "rel", document.getElementById("rel").value);
setAttr(a, "target", document.getElementById("target").value);
setAttr(a, "type", document.getElementById("type").value);
if (document.getElementById("download").checked) {
a.setAttribute("download", "");
}
// Wrap selected content
const contents = range.extractContents();
a.appendChild(contents);
range.insertNode(a);
// Restore selection
selection.removeAllRanges();
const newRange = document.createRange();
newRange.selectNodeContents(a);
selection.addRange(newRange);
}
function setAttr(el, name, value) {
if (value && value.trim() !== "") {
el.setAttribute(name, value.trim());
}
}
function unwrap(el) {
const parent = el.parentNode;
while...