1

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>&#8203;<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');
    }
cjcjcj
  • 11
  • 2

4 Answers4

0

I hope this will help you?

if($('p').html() == "" || $('p').html == "&#8203;"){
    //Do something
}
0

Check if empty the following way:

if ($("Your p tag").val().length == 0) { /* Empty */ }
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
Maxime2400
  • 66
  • 8
0

You can check whether the element has content like this:

checkElementContents(document.getElementById('p1'));
checkElementContents(document.getElementById('p2'));

function checkElementContents(element) {
  if (element.innerHTML) {
    console.log(element.id + " is not empty");
  } else {
    console.log(element.id + " is empty");
  }
};
<p id="p1"></p>
<p id="p2"> </p>
Brad
  • 8,044
  • 10
  • 39
  • 50
0

Be careful with spaces, carriage return etc...

function isEmpty(ele)
{
   var count = ele.html().replace(/\s*/, '');
   if(count>0)
      return false;
   return true;
}

console.log(isEmpty($('p')));
ZiTAL
  • 3,466
  • 8
  • 35
  • 50