Skip to content

Instantly share code, notes, and snippets.

@kuboon
Last active October 10, 2020 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuboon/a33dfacab5ae0824b0d05e250a4381bb to your computer and use it in GitHub Desktop.
Save kuboon/a33dfacab5ae0824b0d05e250a4381bb to your computer and use it in GitHub Desktop.
document.getSelection with img.alt text
function isImg(node: Node):node is HTMLImageElement{
return node.nodeName==='IMG'
}
function selectionToFragment(){
const s = document.getSelection()
const r = s!.getRangeAt(0)
return r.cloneContents()
}
function getTextFromFragment(f: DocumentFragment) {
const walker = document.createTreeWalker(f, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
{
acceptNode: (node) => node.hasChildNodes()
? NodeFilter.FILTER_SKIP
: NodeFilter.FILTER_ACCEPT
}
)
const text: (string | Node | null)[] = [];
let currentNode: Node | null = walker.nextNode();
while (currentNode) {
text.push(isImg(currentNode) ? currentNode.alt : currentNode.textContent);
currentNode = walker.nextNode();
}
return text.join("")
}
function selectionToText(){
return getTextFromFragment(selectionToFragment())
}
function selectionToHtml(){
const div = document.createElement('div');
div.appendChild(selectionToFragment());
return div.innerHTML
}
console.log(selectionToHtml())