Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As suggested in the comments, simply add an else statement to revert back to the <h1>:

window.addEventListener('resize', () => {
  if(window.innerWidth <=1000){
    parentDiv.innerHTML = '<p>lorem Ipsum</p>'
  } else {
    parentDiv.innerHTML = '<h1>My Name</h1>'
  }
})

FYI, using CSS media queries is a lot more efficient than listening to the window resize event:

  • https://css-tricks.com/a-complete-guide-to-css-media-queries/
  • https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!