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>
?
Asked
Active
Viewed 316 times
2

Kyle
- 21,377
- 37
- 113
- 200
4 Answers
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 yeah! this works! but I'm afraid if this is cross-browser... ;) – Reigel Gallarde 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
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 thatis 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();
}
}