Farhan
Farhan

Reputation: 67

Get HTML of selected content

I have a UIWebView i want to introduce functionality of content(may be text or text and images) selection so that the user can email it.
Is there any way to get the HTML code for the given selection using JavaScript? I tried the built-in clipboard of webkit but its seems not working for images selection.May be i am wrong,if there is a way please tell me.

Upvotes: 1

Views: 516

Answers (1)

Tim Down
Tim Down

Reputation: 324567

var range, frag, sel = window.getSelection();
if (sel.rangeCount) {
    range = sel.getRangeAt(0);
    frag = range.cloneContents();
}

This will give you a DocumentFragment containing the selected content. You can traverse the descendants of the fragment using the usual DOM methods. If you must have a literal HTML string, you could then do the following:

var div = document.createElement("div");
div.appendChild(frag);
alert(div.innerHTML);

Note that this last part won't work if the selected contents can't be placed inside a <div> (if, say, the whole body or document was selected).

Upvotes: 2

Related Questions