How to add html code based on the screen sizes using Javascript?

I want to make add some code to the HTML dom according to the screen sizes. I want to totally remove the code when the screen size is something instead of still having the code and doing display: none. How can I do it?

<div id="main">
  <h1>One</h1>
</div>
const main = document.getElementById('main');

if(window.innerWidth <= 400) {
       main.innerHTML = '<h2>Added By js</h2>';
 }
 else {
 main.innerHTML = '';
 }