Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda