hendry91 hendry91 - 6 months ago 26
jQuery Question

efficient way to remove empty div

I'm using

<div contenteditable="true">
, when I press enter to newline with empty input, it will generate
<div><br></div>
.
But I just want to remove it from beginning and at the end.

For example:


<div contenteditable="true">


<div><br></div>
i want to remove this

abc

<div><br></div>
remain

1234

<div><br></div>
i want to remove this

<div><br></div>
i want to remove this

</div>



for(var x = item.length - 1 ; x >= 0 ; x--){
if($(item[x]).html() == "<br>"){
$(item[x]).remove();
}else{
break;
}
}

for(var x = 0; x <= item.length-1 ; x++){
if($(item[x]).html() == "<br>"){
$(item[x]).remove();
}else{
break;
}
}


Currently I'm using two looping to remove it, But I'm looking a better way to filter it.
Anyone can guide me?

Thanks.

Answer

You can actually achieve it with while loop instead of for loop. You need to store the reference for first and last child of the contenteditable div and manipulate it with while loop. Detailed explanation in comments around the code.

$('.remove').on('click', function() {
  var firstChild = $('div[contenteditable] div:first');
  var lastChild = $('div[contenteditable] div:last');
  //store the reference for first and last child of the contenteditable div
  while(firstChild.html()=="<br>")//remove all the element's until firstchild's html!="<br>" i.e. is not empty
  {
   firstChild.remove();//remove it
   firstChild= $('div[contenteditable] div:first'); //again store the reference to new first child after remove
  }
  //same goes with last child
  while(lastChild.html()=="<br>")
  {
   lastChild.remove();
   lastChild= $('div[contenteditable] div:last');
  }
})
div[contenteditable] {
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true">

</div>
<button type="button" class="remove">Remove unwanted</button>