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

235
Views
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 answers
Answer question

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 Report

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 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!