2

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>?

Kyle
  • 20,701
  • 36
  • 109
  • 197

4 Answers4

3

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.

simplyharsh
  • 33,714
  • 12
  • 61
  • 70
  • +1 yeah! this works! but I'm afraid if this is cross-browser... ;) – Reigel Aug 10 '10 at 06:48
  • Not, it's not cross-browser, it's far far away from beeing cross-browser. @simplyharsh: You really should mention that in your answer! – jAndy Aug 10 '10 at 07:03
1

You need to deal with window.getSelection().

See

Community
  • 1
  • 1
jAndy
  • 223,102
  • 54
  • 301
  • 354
0
$('h1').click(function(){
   alert(this); // `this` is the <h1> object clicked.
});

is there some tricky part I missed in your question?

Reigel
  • 62,834
  • 21
  • 119
  • 135
  • I think he means if you select text within the object. I.e. in `

    Foo Rar

    `, if you just highlight `Rar`, then he wants to knock that

    is the DOM object with the highlighted text.

    – djdd87 Aug 10 '10 at 06:38
  • @GenericTypeTea - but then, how would you highlight? with the `DOM` I guess you should click then highlight.. ;) – Reigel Aug 10 '10 at 06:41
0

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();
    }
}
Community
  • 1
  • 1
Tim Down
  • 306,503
  • 71
  • 443
  • 520