Javascript: Selection

sel = document.getSelection()

ran = sel.getRangeAt(0)

df = ran.cloneContents()
df = ran.extractContents()

// create highlight element
sp = document.createElement("span")

// set highlight color
sp.style.backgroundColor = "red"

// add document fragment to highlight element
sp.append(df)

// we need to get reference to the parent element where the selection start
parent_el = sel.anchorNode.parentElement
sel_anchor = sel.anchorOffset

// we remove the selection from the parent element
sel.deleteFromDocument()

// we extract the content of parent element
parent_txt = parent_el.innerHTML

// we get the text before the selection
begin = parent_txt.substring(0, sel_anchor)
end = parent_txt.substring(sel_anchor)

// we put it back into the parent element
parent_el = begin + sp.outterHTML + end
sel = document.getSelection()

ran = sel.getRangeAt(0)

hl = new Highlight(ran)

CSS.highlights.set('test-hl', hl)

document.getElementsByTagName("style")[0].innerHTML += "::highlight(test-hl) { background-color: yellow; }"
::highlight(test-hl) {
  background-color: yellow;
}
tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT)

while (tw.nextNode()) {
	if (tw.currentNode == "start text") {
    	startNode = tw.currentNode
    }
    
    if (tw.currentNode == "end text") {
    	endNode = tw.currentNode
        return;
    }
}

ran = new Range()

ran.setStart(startNode, startOffset)
ran.setEnd(endNode, endOffset)

sel = document.getSelection()

sel.addRange(ran)

References:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *