views:

71

answers:

4

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

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

is there some tricky part I missed in your question?

Reigel
I think he means if you select text within the object. I.e. in `<h1>Foo Rar</h1>`, if you just highlight `Rar`, then he wants to knock that <h1> is the DOM object with the highlighted text.
GenericTypeTea
@GenericTypeTea - but then, how would you highlight? with the `DOM` I guess you should click then highlight.. ;)
Reigel
+2  A: 

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
+1 yeah! this works! but I'm afraid if this is cross-browser... ;)
Reigel
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
+1  A: 

You need to deal with window.getSelection().

See

jAndy
A: 

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: http://stackoverflow.com/questions/1335252/how-can-i-get-the-dom-element-which-contains-the-current-selection/1336922#1336922

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();
    }
}
Tim Down