I have a fiddle showing what my code is doing. Using javascript/jquery I am trying to insert a table into a content editable div at the current caret position. I am using Tim Down's Rangy library to accomplish this. I am doing this with the following javascript.
var range = getFirstRange();
var el = document.createElement("table");
var tableHtml = "";
for (var a = 0; a <= tableY; a++) {
if(a%2==0){
tableHtml += '<tr class="zebra">';
}
else{
tableHtml += '<tr>';
}
for (var b = 0; b <= tableX; b++) {
tableHtml += '<td> </td>';
}
tableHtml += '</tr>';
}
$(el).html(tableHtml);
range.insertNode(el);
rangy.getSelection().setSingleRange(range);
Just in case it helps here is the getFirstRange function.
function getFirstRange() {
var sel = rangy.getSelection();
return sel.rangeCount ? sel.getRangeAt(0) : null;
}
I need to make valid html wherever this table is placed. for example if the caret is in the middle of a link I am trying to avoid the following html.
<p>some text <a href="#">text
<table>
<tr>
<td>table content</td>
</tr>
</table>
text</a> more text</p>
I would like it to look like this instead.
<p>some text <a href="#">text</a></p>
<table>
<tr>
<td>table content</td>
</tr>
</table>
<p><a href="#">text</a> more text</p>
`. The browser does this because it can't house blocks and weirdness `display`-modes (like tables) inside inline elements.
– Apr 17 '13 at 21:31