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

237
Visualizações
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 = '';
 }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Simply use the @media screen of css, I think you need to do this:

h1{
   display: block;
  }
 h2{
   display: none;
  }

@media screen (max-width: 400px) {
 h1{
   display: none;
  }
 h2{
   display: block;
  }
 }

doing this you tell the browser to set display:none of the h1 when the screen width is over 400px, you can do it too with height

about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to do it with javascript, all you're missing are the events that will trigger your code

function yourFunction() {
    const main = document.getElementById('main');

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

window.onload = yourFunction;
window.onresize = yourFunction;
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