Reputation: 216
Every time I try it gives me a p
tag even doe the parent should be a span
var sel = window.getSelection();
console.log(sel.getRangeAt(0));
Is there any solution or a way to do it or got a link to some useful information how to do it?
Upvotes: 0
Views: 758
Reputation: 2924
Use the range
properties startContainer, endContainer and commonAncestorContainer to determine the selection containing elements.
In the following example select the text "bbb" and press the button "press me". The commonAncestorContainer
is span
element as expected:
$('#pressme').click(function(){
var rng = window.getSelection().getRangeAt(0);
alert(rng.commonAncestorContainer.parentNode.tagName);
});
#editor {
width: 500px;
height: 400px;
padding: 4px;
border: solid 1px gray;
margin-bottom: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='editor' contenteditable='true'>aaa <span style="color:red">bbb</span> ccc</div>
<input id='pressme' type='button' value='press me' />
Try to select various portions of text and see how it changes the result.
Upvotes: 1