I build my custom wysiwyg with pure javascript without other library. I had 1 problerm once insert HTML to contenteditable then hit enter to create newline.
I wan't every first child element or text paragraph in my contenteditable wrapped by div.para
.. Below is some code to explain what I wan't.
<div class="wysiwyg-content" id="post-editor" contenteditable="true">
<div class="para">My first paragraph</div>
<div class="para"><br></div>
<div class="para"><a href=""><img src=""/></a></div>
<div class="para"><figure class="gallery><a href=""><img src=""/></a></figure></div>
<div class="para">or what ever entities wrapped with div.para</div>
</div>
I also use/executed codes below after some event (ex: paste, insert HTML through javascript) to make sure cursor placed at the end of contenteditable with expectations once hit enter to create newline, it does not create unwanted structure/element tag, always create <div class="para">[cursor placed here]</div>
.
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
// I used code below to executed AFTER insert HTML to conteneditable.
placeCaretAtEnd( document.getElementById("post-editor") );
I think javascript above not enough to complete my goal. Because, after insert some HTML through javascript to contenteditable THEN HIT ENTER (cursor look at end of my contenteditable); it will be create element and follow last tag of element INSIDE div.para
. ex: insert <div class="para"><figure class="gallery><a href=""><img src=""/></a></figure></div>
html, then hit enter will become <div class="para"><figure class="gallery><br>[possible cursor here]</div>
. What I wan't everytime hit enter contenteditable create new element <div class="para">[then cursor placed here]</div>
.
How to do that with Pure Javascript? Thanks in advance.