Created
August 13, 2014 12:51
-
-
Save aloncarmel/128d1b076beb89f8b9b8 to your computer and use it in GitHub Desktop.
Insert html into textnode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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