Nic Hubbard
Nic Hubbard

Reputation: 42139

Get HTML element contained in range

I am using document.getSelection() to select some text. I would like to know what type of element the selected range contains (I specifically want to see if it is an anchor tag).

var selection = document.getSelection();
var range = selection.getRangeAt(0);

So I can get the range, but how can I know what element is in that range? Happy to use plain js or jQuery.

EDIT:

Here is what I came up with:

var updateLink = function(url) {

    var selection = document.getSelection();
    var range = selection.getRangeAt(0);
    if (range != 0) {
        var containerElement = range.commonAncestorContainer;
        if (containerElement.nodeType != 1) {
            containerElement = containerElement.parentNode;
            var e = $(containerElement);
            e.attr('href', url);
        }

    }

}//end

Upvotes: 6

Views: 3127

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

You could use cloneContents() method:

DEMO

$(document).mouseup(function(){
    var range = window.getSelection().getRangeAt(0),
        selectionContents = range.cloneContents();

    alert($(selectionContents.childNodes).filter('a').length);
});

Upvotes: 1

Ringo
Ringo

Reputation: 3965

Try this:

var obj = document.getSelection();
var parentNode = $(obj.anchorNode).parent();

Here is jsfiddle

Upvotes: 2

Related Questions