Skip to content

Instantly share code, notes, and snippets.

@mumoshu
Last active December 18, 2019 01:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mumoshu/4591792 to your computer and use it in GitHub Desktop.
Save mumoshu/4591792 to your computer and use it in GitHub Desktop.
選択範囲の文字列を取得するjs
// See: Introduction to Range
// http://www.quirksmode.org/dom/range_intro.html
var range = document.createRange();
// In which DOM node does the Range start or end?
range.setStart(selectionObject.anchorNode, selectionObject.anchorOffset);
// At which text offset does the Range start or end? The text offset is the position of the first or last character in the text node that's part of the Range.
range.setEnd(selectionObject.focusNode, selectionObject.focusOffset);
// See: javascript - Find all text nodes - Stack Overflow
// http://stackoverflow.com/questions/9178174/find-all-text-nodes
function doSomething(element) {
console.log("type:" + typeof element, "class:" + element, "content:", element);
}
function recurse(element)
{
if (element.childNodes.length > 0)
for (var i = 0; i < element.childNodes.length; i++)
recurse(element.childNodes[i]);
if (element.nodeType == Node.TEXT_NODE && /\S/.test(element.nodeValue))
doSomething(element);
}
var html = document.getElementsByTagName('html')[0];
recurse(html);
var range = window.getSelection().getRangeAt(0);
range.endContainer.textContent.slice(range.startOffset, range.endOffset);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment