rubyist
rubyist

Reputation: 3132

How to get the tagname and its href of selected anchor text

When I select a link (with no ids or classes) within a paragraph, I need to get the selected links href value. How do I do it in jQuery? I am using document.getSelection() method for that. But I don't see any method in document.getSelection() which returns the href value.

When I select the link by dragging the mouse, I am able to get the href value like below.

currentLink = document.getSelection().anchorNode.parentElement.href;

But when I select the link by double clicking the text, the above command will not return the href value. Please help.

Upvotes: 1

Views: 661

Answers (1)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

Here, I wrote you a little something to get you started. It's more cross-browser than your original code:

(function(AnchorSelector, $, undefined) {

    AnchorSelector.getAnchorHrefs = function(e) {
        var container = '';
        if (window.getSelection) {
            var sel = window.getSelection();
            if (sel.rangeCount) {
                var div = $('<div>');
                for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                    div.append(sel.getRangeAt(i).cloneContents());
                }
                container = div;
            }
        } else if (document.selection) {
            container = $('<div>').append(document.selection.createRange().htmlText);
        }
        var arr = $.map(container.find('a'), function(n, i) {
            return ($(n).attr('href'));
        });
        if (arr.length) {
            alert(arr.join(','));
        }
        // Note: you can check e.type to see if it was a 'dblclick' or a 'mouseup' 
        // you may need to employ some type of debouncing to not get two alerts
        // when you double click the text
    }

    $(function() {
        $(document)
            .dblclick(AnchorSelector.getAnchorHrefs)
            .mouseup(AnchorSelector.getAnchorHrefs);
    });

})(window.AnchorSelector = window.AnchorSelector || {}, jQuery);

​And here's a jsFiddle demo.

Upvotes: 1

Related Questions