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>?
views:
71answers:
4
A:
$('h1').click(function(){
alert(this); // `this` is the <h1> object clicked.
});
is there some tricky part I missed in your question?
Reigel
2010-08-10 06:35:57
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
2010-08-10 06:38:00
@GenericTypeTea - but then, how would you highlight? with the `DOM` I guess you should click then highlight.. ;)
Reigel
2010-08-10 06:41:00
+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
2010-08-10 06:39:42
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
2010-08-10 20:36:22