How can I change element constantly based on window.innerWidth resize?

Viewed 26

I want to change element dynamically according to window width. It should change to a new element when condition is met, as well as revert back to the original element when window is restored to its original size. Here's my code attached:

HTML

<div>
  <h1>My Name</h1>
</div>

JS

const parentDiv = document.querySelector('div');

console.log(window.innerWidth);
window.addEventListener('resize', () => {
  if(window.innerWidth <=1000){
      parentDiv.innerHTML = '<p>lorem Ipsum</p>'
    }
})

But here, after changing back the window size to a width of >1000px, the div tag still holds p tag instead of reverting back to the original h1 tag. Should I add another event listener for this specific task? Or is there any other method of window object by which we can achieve this?

1 Answers
Related