神刀安全网

Remove child elements with JavaScript

When you’re using views that update based on different user interaction, you sometimes have to remove the child element of an element before filling it with new data and the new view. Now I know, you don’t need these methods when you’re using Angular, ReactJS or something like that. But I do not use these tools all the time and most often rely on plain Javascript when working on my projects. So what’s the best way to remove child elements of a wrapping element?

There are actually two ways on removing the child elements:

// Method 1 document.getElementById('foo').innerHTML = '';  // Method 2 var node = document.getElementById('foo');  while(node.firstChild){     node.removeChild(node.firstChild); }

I have encountered method one many times during my research on the internet and improving existing products. It sound the most straight forward one but actually it is not the best method to pick

It’s all about performance

The first methods doesn’t update the DOM because it evaluates to a string. The removeChild() function  however does update the DOM and makes it therefor way faster. According to latest statistics even 2x times faster. That’s a difference you cannot ignore!

Remove child elements with JavaScript

Because method 1 updates the DOM you can easily acces the new elements with the same functions but with different data. This makes your online product much more stable to use.

But you could use jQuery?

Yes you could, but the funny thing is that jQuery uses the same method as I do, method 1. They weren’t born yesterday ;).

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Remove child elements with JavaScript

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址