Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda