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
  • 21,377
  • 37
  • 113
  • 200

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
  • 35,488
  • 12
  • 65
  • 73
1

You need to deal with window.getSelection().

See

Community
  • 1
  • 1
jAndy
  • 231,737
  • 57
  • 305
  • 359
0
$('h1').click(function(){
   alert(this); // `this` is the <h1> object clicked.
});

is there some tricky part I missed in your question?

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • 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 Gallarde 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
  • 318,141
  • 75
  • 454
  • 536