Your code appears to depend on this
referring to the #todo-list
element:
if ( $('#todo-list').children().length <= 0 ) {
$(this).append("<p>You have no tasks</p>");
}
...but in the context you're calling it, this
probably refers to the window object instead. Variable scoping in javascript is complicated enough that I'm going to defer to others who are much better than I at explaining it.
But we can bypass all that anyway, because in this case, you can let jQuery selectors do most of the work: they will implicitly iterate over every matching element to run any chained functions, such as appending your message:
// using a classname instead of an ID, since I have two lists:
$('.todo-list:empty').append('<li>You have no tasks</li>');
// (Remember also that you can't append a `<p>` to a `<ul>`!)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="todo-list">
<li>One</li>
<li>Two</li>
</ul>
<ul class="todo-list"></ul>
:empty
isn't the same thing as "has no children", though. (Text nodes count as contents, so :empty
only matches elements which contain nothing at all, even whitespace.) If your code contains inconvenient whitespace you could use this slightly more complicated selector, which will match a .todo-list
element which does not contain <li>
elements:
$('.todo-list:not(:has(li))').append('<li>You have no tasks</li>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="todo-list">
<li>One</li>
<li>Two</li>
</ul>
<ul class="todo-list"></ul>
Hypothetically, if the condition you're testing were something that couldn't be easily contained in a path selector, you can chain a .each()
after a simpler selector (it can be reasonable to do this even when you know there's only one element, because the same code will work correctly for any number of elements, even zero). Inside that function scope, jQuery uses this
to refer to the current DOM element:
//out here, `this` refers to the window.
$('.todo-list').each(function() {
// inside the context of this function, `this` refers to the DOM element currently being iterated over.
if ($(this).children().length === 0) {
$(this).append('<li>You have no tasks</li>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="todo-list">
<li>One</li>
<li>Two</li>
</ul>
<ul class="todo-list"></ul>