Leaman
Leaman

Reputation: 25

Javascript: Deleting elements that were created with .createElement()

So when a user presses a button, I am creating elements to make a list appear on the page. However, when they press the button again the new list goes after the previous content, and the old content remains. I need to clear the previous content (which was created with .createElement()), and then insert the fresh content.

This is how I'm making the elements:

I have a <ul id="positiveUL"> in the HTML. And positiveList = document.getElementById('positiveUL')

for(var positive in positives) {
    var li = document.createElement('li');
    li.innerHTML = positives[positive] + ', ';
    positiveList.insertBefore(li, positiveList.firstChild);
}

What I have tried:

.innerHTML = ' ';

I also tried removing childNodes with .removeChild(), but it doesn't work.

Would really appreciate any help or direction to go in. Thanks!

Upvotes: 1

Views: 89

Answers (1)

Dan H
Dan H

Reputation: 626

Hopefully I understand you, but before inserting your new content, empty the old content?

while(node.firstChild) 
{
    node.removeChild(node.firstChild);
}

Where node is your parent node?

Upvotes: 1

Related Questions