1

I am dynamically generating a table and after that I want to append it as a child to a div. The problem is every time i regenerate the table it gets appended in the same div without the old table removed.

if(context.children.length == 0){
    context.appendChild(table);
}else{
    context.replaceChild(table);
}

I tried with checking if the child already exists and if it does i replace it with the new element. But I get the error The argument is not optional and I don't know how to do it otherwise. Any ideas?

3
  • 2
    replaceChild method should have 2 args .... new and old child Commented Nov 11, 2016 at 9:02
  • Thank you. Sorry for the stupid question. As I have only one child I have not thought about this. Commented Nov 11, 2016 at 9:07
  • Can you make a normal answer that I can mark the question as solved? Commented Nov 11, 2016 at 9:07

2 Answers 2

1

That's not how replaceChild() works, You should, paremtElement.replaceChild(new element, element to be replaced) https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild

Sign up to request clarification or add additional context in comments.

Comments

1

You need to provide the second argument as the child to be replaced in Node#replaceChild method.

if(context.children.length == 0){
    context.appendChild(table);
}else{
    context.replaceChild(table, context.children[0]);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.