I need to ask for some help with this one so here goes...
I'm creating a WYSIWYG editor using a contenteditable textarea. It automatically creates paragraphs and you can also add in subtitles.
What I would like to be able to do is when the button #addStorySubtitle
is clicked, if the currently selected p tag is empty or only contains a zero width space ​
, then it will be replaced with the contents of innerDivSubtitle. However, if the p tag has content, use innerDivSubtitle
to create a new block level element underneath.
The part I seem to be having trouble with is detecting is the p tag is empty.
Thanks all!
$('#addStorySubtitle').click(function(e){
var innerDivSubtitle = $('<div class="addStorySubtitleWrap" contenteditable="false"><span class="removeStorySubtitle"></span><textarea name="addstorysubtitle" class="addStorySubtitle autoSize" placeholder="Really good subtitle" contenteditable="true"></textarea></div><p>​<p>');
var sel = window.getSelection();
if ($(sel.anchorNode.parentNode) === "") {
alert('empty'); //just for help
$(sel.anchorNode.parentNode).replaceWith(innerDivSubtitle);
} else {
alert('not empty'); //just for help
$(sel.anchorNode.parentNode).after(innerDivSubtitle);
}
});
UPDATE
Thanks for all of your helpful replies!
It turns out that the zero width space detection was causing the issue and I had to use unicode to detect it. Here's what I did to fix it...
var nodCon = $(sel.anchorNode.parentNode).html();
if (nodCon === "" || nodCon === "\u200b"){
alert('empty');
}