ReynierPM ReynierPM - 23 days ago 7
Javascript Question

DIV isn't show up upon DOM element removing, does the function knows about the DOM element removal?

I have the following piece of code:

<ul class="ul" id="selected_conditions">
<li class="condition" data-field="asset_locations_name" data-condition="in">
<i class="fa fa-minus-circle delete_condition" aria-hidden="true" title="Click to remove this condition from the list"></i> WHERE asset_locations_name IN(
<span class="condition_item" data-id="1213381233">
<i class="fa fa-minus-circle delete" title="Click to remove this item from the list" aria-hidden="true"></i> 1213381233
</span>,
<span class="condition_item" data-id="1212371897">
<i class="fa fa-minus-circle delete" title="Click to remove this item from the list" aria-hidden="true"></i> 1212371897
</span> )
</li>
</ul>

<div id="empty_msg" style="display: none">
There is no conditions
</div>


Once I click on the little icon
.delete_condition
I should remove the
li
element and if it's the last one at
#selected_conditions
then remove the
display: none
from the
#empty_msg
DIV. This is how I am doing it:

$(function() {
$('#selected_conditions').on('click', '.delete_condition', function() {
var condition = $(this).closest('.condition');
var conditions = $('#selected_conditions li');

$.confirm({
title: 'Confirm!',
icon: 'fa fa-warning',
closeIcon: true,
closeIconClass: 'fa fa-close',
content: 'This will remove the whole condition! Are you sure?',
buttons: {
confirm: function() {
condition.remove();

if (conditions.length == 0) {
$('#empty_msg').removeAttr('style');
}
}
}
});
});
});


It removes the
li
but doesn't show up the
#empty_msg
since
conditions.length
still
=1
. I have debug the code in Chrome Console and that's the result and I don't know why.

Why? Doesn't know the function or the DOM that the element has been removed? How I can fix this behavior?

Maybe is me doing something wrong and if that's the case I couldn't find where I am messing up things.

I am using jQuery Confirm for the dialogs.

Here is a Fiddle to play with.

Answer

You'have to query items after removing it but you're doing it before removing the item and as a result it's counting length before it was removed.

var conditions = $('#selected_conditions li');

You can just update your condition to this to get expected result.

if ( $('#selected_conditions li').length == 0) {
  $('#empty_msg').removeAttr('style');
}

Here is the working updated fiddle. https://jsfiddle.net/8184ok2e/11/

Comments