user2066880
user2066880

Reputation: 5024

How does JQuery empty() method work?

I know that the empty method removes all children in the DOM element.

In this example however, why does removing the empty method result in duplicate entries:

enter image description here

and putting it in results in a normal page:

enter image description here

var renderNotesList = function() 
{
    var dummyNotesCount = 10, note, i;

    var view = $(notesListSelector);
    view.empty();

    var ul = $("<ul id =\"notes-list\" data-role=\"listview\"></ul>").appendTo(view);

    for (i=0; i<dummyNotesCount; i++) 
    {
        $("<li>"+ "<a href=\"index.html#note-editor-page?noteId=" + i + "\">" + "<div>Note title " + i + "</div>" + "<div class=\"list-item-narrative\">Note Narrative " + i + "</div>" + "</a>" + "</li>").appendTo(ul);
    }
    ul.listview();
};

Upvotes: 1

Views: 237

Answers (2)

Marc Audet
Marc Audet

Reputation: 46795

Without seeing how your JavaScript is being used in your page, I suspect that you must be calling the renderNotesList() function twice and thus generating to unordered lists.

When you use the .empty() method, you are removing the first ul list, so you only see one instance. Without the call to .empty(), you retain both.

However, I can't say where or how this is happening in you web page without seeing more, but at least you now have some idea of what to look for.

Demo Fiddle

I built a demo using your JavaScript, but I was sort of guessing as to how you are using it.

Fiddle: http://jsfiddle.net/audetwebdesign/UVymE/

Footnote

It occurred to me that the function ul.listview() may actually be appending a second copy of the ul to the DOM. You need to check the code or post it for further review.

Upvotes: 0

furas
furas

Reputation: 142909

I don't know why empty() doesn't work but I found this

... so until this is sorted everyone should just use: el.children().remove(); instead of el.empty();

( jQuery.empty() does not destroy UI widgets, whereas jQuery.remove() does (using UI 1.8.4) )

Upvotes: 2

Related Questions