If you only want to get links that are in "a" tags you can just do something like this:
function getLinksFromSelection() { if (window.getSelection) { var selection = window.getSelection(); if (selection.rangeCount > 0) { var range = selection.getRangeAt(0); var div = document.createElement('DIV'); div.appendChild(range.cloneContents()); var links = div.getElementsByTagName("A") for (var i=0; i < links.length; i++) { console.log(links[i].href); } } }
If you also want to take into account a selection that is contained within a link (i.e. the link is a parent node to the selection) then you'd add something like this:
var alink = range.commonAncestorContainer; if (alink.nodeType == 3) { // if text node then get parent alink = alink.parentNode; } if (alink.tagName === 'A') { console.log(alink.href) }
Here's the fiddle: http://jsfiddle.net/ESr3C/
window.getSelection()to pick out links.window.getSelection()? tried.outerHTMLbut it'snull