How to Avoid Empty Clear Divs

Are empty divs OK?

I'am pretty sure no browser 'ignores' an empty divs. I would add a 100% width just to be sure it works.

efficient way to remove empty div

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>

How to clear all div s’ contents inside a parent div ?

jQuery('#masterdiv div').html('');

Prevent divs from filling empty space?

Float both .display-label and .display-field to the left, float: left; and add clear: left; to .display-label. I removed the margin from .display-field and added some padding.

The clear: left; will prevent all the divs from lining up in a single line and push it down below the div preceding it.

Here is an updated fiddle: http://jsfiddle.net/Zwfzp/4/

CSS

.display-label
{
float:left;
width: 150px;
text-align:right;
font-size:small;
font-weight:bold;
clear: left;

}

.display-field
{
float: left;
font-size:small;
padding-left: 10px;
}

How to remove all empty or space div on page?

You can use filter in jQuery. This way you can set your own definition for "empty".

$(function() {

var empties = $('div').filter(function(){

return $(this).html().trim() == '';

});



alert(empties.length);

empties.remove();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="fl-no-pad" style="display: block;">

</div>


Related Topics



Leave a reply



Submit