简体   繁体   中英

Javascript to Jquery convertion, removing first child every iteration

I'm rewriting some old projects with Jquery to learn it better, I managed to do everything except for this while loop. It should loop through a container of divs and remove the first child every time.

var calendarModel = {
    siteContainer: $('#calendar-container')
}

while (calendarModel.siteContainer.firstChild) {
    calendarModel.siteContainer.removeChild(calendarModel.siteContainer.firstChild);
}

My first (horrible) attempt yielded no result except for an infinite loop:

var firstDiv = $('div:first-child', calendarModel.siteContainer);

while (firstDiv) {
    firstDiv.remove();
}

Then I tried this:

var firstDiv = $('div:first-child', calendarModel.siteContainer);

while (calendarModel.siteContainer.firstDiv) {
    calendarModel.siteContainer.firstDiv.remove();
}

Which was even worse cuz then it doesn't even enter the loop.

I also tried without the loop to see if it removed anything at all:

var firstDiv = $('div:first-child', calendarModel.siteContainer);
    firstDiv.remove();

However, it didn't. I'm really stuck so I'd appreciate some help on this one. Any ideas?

It is dangerous with jQuery to remove nodes using the native api since it can cause memory leaks.

Instead use a jQuery method so that data is cleaned up.

calendarModel.siteContainer.children().remove();

Loops have to have a test condition in them. They loop through until that test condition is no longer true. So assuming your firstDiv selector has an array of div's

var i = 0;
while(firstDiv.length > i){
   console.log(firstDiv[i]);
   i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM