Edit: Since you need this for a FF extension you can skip all the functions for IE and everything you need to do is this:
window.getSelection().getRangeAt(0).commonAncestorContainer
More information about Ranges: https://developer.mozilla.org/en/DOM/range
There already is a similar question:
Get selected text and selected nodes on a page?
I modified the functions a bit:
<script type="text/javascript">
function getTextSelection() {
if(document.selection)
return document.selection;
else if(window.getSelection)
return window.getSelection();
else if(document.getSelection)
return document.getSelection();
else
return false;
}
function getSelectionRange() {
var selection = getTextSelection();
if(selection.getRangeAt)
return selection.getRangeAt(0);
else if (selection.createRange)
return selection.createRange();
else
return false;
}
function getSelectionParent(r) {
if(r.parentElement)
return r.parentElement;
else if(r.commonAncestorContainer)
return r.commonAncestorContainer;
else
return false;
}
</script>
HTML:
<body>
<p><em>This is just some random text. </em><strong>Select me and then click the button!!!</strong></p>
<p><input type="button" value="Parent element?" onclick="alert('The selection\'s parent element is: ' + getSelectionParent(getSelectionRange()).nodeName);" /></p>
</body>
I tested this stuff in IE6,7 and FF3.0. Worked without any problems. The only thing you must be aware of is that IE unlike FF ignores text nodes.
If you want to try it out yourself: http://dev.freedig.org/files/selection.html