javascript/WYSIWYG parentElement returning div instead of p element
I am trying to build a WYSIWYG editor with javascript using contentEditable=true. The point which I'm stucked is 开发者_开发问答that on IE document.selection.createRange().parentElement() returns the element that contenteditable is set to true. For an easier comprehension I'll give you an example:
<div contenteditable="true">
<p>lorem ip|sum dolor</p>
</div>
In this example the ' | ' represents the caret. While in chrome when I use the commonAncestorContainer the returning element is p in this example, in IE parentElement returns the container div. In my understanding the browser is ignoring the elements and therefore I cannot figure out on what element is the focus. I won't ask "if there is any way" since I've seen pretty good working WYSIWYG editors, therefore my question is how can I get the "real" parent element in this example? :)
Ah btw, since I'm a new user I can't create tags. I believe "parentElement" would be a good tag for this question.
DOM Range
's commonAncestorContainer
and TextRange
's parentElement()
are slightly different: commonAncestorContainer
returns the deepest node (which could be a text node) that contains the whole range while parentElement()
returns the deepest element that contains the whole TextRange. In your example, commonAncestorContainer
would be the text node "lorem ipsum dolor" while parentElement()
would return the <p>
element. If that's what you want, you can get that with Range by checking commonAncestorContainer
's nodeType:
var containerElement = range.commonAncestorContainer;
if (containerElement.nodeType == 3) {
containerElement = containerElement.parentNode;
}
精彩评论