I click to the table on 'Smith' text
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
</tr>
</table>
and I call method:
var selection = editor.getSelection();
var element = new CKEDITOR.dom.element('span');
editor.insertElement(element);
widget = editor.widget.initOn(element, 'myWidget');
And it will create new widget on exact position, where I click (next to text 'Smith').
But I want to create this widget first cell in corespondent row.
Output should be something like:
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td><span>myWidget</span>Jill</td>
<td>Smith</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
</tr>
</table>
How can I achieve that ?
You can either move selection before insertElement
to position where actually you wish to insert the element. Insert element method use current selection as place to insert. To do so you need to create new range, add proper element to range (as startNode), use collapse selection, and then make selection from range. Right now you should have selection in place where element should be inserted.
Another option (for me a little bit more convenient) might be replace insertElement
with method which place widget in proper place. It supposed to works sth like:
var selection = editor.getSelection();
var element = new CKEDITOR.dom.element( 'span' );
var firstCell = selection.getStartElement().getAscendant( 'tr' ).getFirst();
firstCell.append( element, true );
Of course code is dedicated for tables only, as tr
is searched in ascendant nodes. I've done this in such way to prevent of situation that selection is inside some bold, linked, emphasized text. So parent doesn't have to be a td
.
More element methods you can find in documentation: https://docs.ckeditor.com/ckeditor4/latest/api