Kyle
Kyle

Reputation: 22035

Javascript/Jquery - How do I get the element that the user has selected with their cursor?

If the user highlights the text within an <h1> with their cursor, how do I get that <h1> object? Or if they selected text within an <li>, how do i get that <li>?

Upvotes: 2

Views: 331

Answers (4)

Tim Down
Tim Down

Reputation: 324547

You can get the parent element of a selection in all modern mainstream browsers as follows. Bear in mind that Firefox allows multiple selections by default these days; this code will use only the first.

See also my answer here: How can I get the DOM element which contains the current selection?

function getSelectionContainerElement() {
    var sel, el;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt) {
            if (sel.rangeCount) {
                el = sel.getRangeAt(0).commonAncestorContainer;
                return (el.nodeType == 3) ? el.parentNode : el;
            }
        } else {
            // This happens in old versions of Safari. A workaround
            // exists, if you need it
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange().parentElement();
    }
}

Upvotes: 0

jAndy
jAndy

Reputation: 235992

You need to deal with window.getSelection().

See

Upvotes: 1

simplyharsh
simplyharsh

Reputation: 36373

You can get the selection on Document as,

dd = window.getSelection();
desiredElement = dd.focusNode.parentNode; // h1 or li or other 
desiredTag = desiredElement.tagName; // its tagname

Happy Coding.

Upvotes: 3

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

$('h1').click(function(){
   alert(this); // `this` is the <h1> object clicked.
});

is there some tricky part I missed in your question?

Upvotes: 0

Related Questions