Skip to content

Instantly share code, notes, and snippets.

@aloncarmel
Created August 13, 2014 12:51
Show Gist options
  • Save aloncarmel/128d1b076beb89f8b9b8 to your computer and use it in GitHub Desktop.
Save aloncarmel/128d1b076beb89f8b9b8 to your computer and use it in GitHub Desktop.
Insert html into textnode
var selection = document.getSelection();
var cursorPos = selection.anchorOffset;
var oldContent = selection.anchorNode.nodeValue;
var toInsert = '_BUTTON_';
var newContent = oldContent.substring(0, cursorPos) + toInsert + oldContent.substring(cursorPos);
var replacehtml = '<button class="btn btn-default">A button</button>';
selection.anchorNode.nodeValue = newContent;
$(document.getSelection().anchorNode.parentElement).contents().each(function() {
if(this.nodeType == 3) {
var u = this.nodeValue;
var reg = /_BUTTON_/g;
$(this).replaceWith(u.replace(reg,replacehtml));
}
});
@alisson04
Copy link

Thank you dude, very nice. i have a problem here, if i try to insert the HTML in a row that have no one character will give a problem:
Uncaught TypeError: Cannot read property 'substring' of null at append2

It happen because the 'substring' cannot read a null, have anyway to avoid the null?

Thank you so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment