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

259
Views
Javascript: Replace a Shown Div with another Hidden Div with Button onclick

i want to replace a div that is already displayed with another Hidden div with just one click. i don't want it to toggle. below is the code.

<html>

<script type="text/javascript">
function show(elementId) { 
 document.getElementById("surf").style.display="none";
 document.getElementById(elementId).style.display="block";
}
</script>

<div id="mode" style="display: visible;">Display By Default</div>

<div id="surf" style="display: none;">Display On Click</div>
<br/>
<button type="submit" id="submit" onclick="show('surf');" name="submit">Submit</button>
</html>

My desired output should be Display On Click when i click the button.

But right now i'm having both Display By Default and Display On Click showing when i click the button display by default at the top and Display On Click at button. i just want Display By Default to be replaced with Display On Click on same line.

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

0

<!DOCTYPE html>
  <html>
  <body>
    <div id="div1" style="display:block">
    <h2>first div</h2>
</div>
<div id="div2" style="display:none">
    <h2>second div</h2>
</div>
<button onclick=show()>click here</button>
</body>
<script>
function show() {
    let div1 = document.querySelector('#div1');
    let div2 = document.querySelector('#div2');

    if (div1.style.display == "block") {
        div1.style.display = "none";
        div2.style.display = "block";
    } else {
        div1.style.display = "block";
        div2.style.display = "none";
    }

  }
</script>
</html>

onclick to hide div1 and show div2, Next click hide div2 and show div1.

about 4 years ago · Juan Pablo Isaza Report

0

You are targeting the wrong element here document.getElementById("surf").style.display="none";. The "surf" should be "mode" instead. This worked for me

function show(elementId) { 
    document.getElementById("mode").style.display="none";
    document.getElementById(elementId).style.display="block";
}
<div id="mode" style="display: visible;">Display By Default</div>
<div id="surf" style="display: none;">Display On Click</div>
<br/>
<button type="submit" id="submit" onclick="show('surf');" name="submit">Submit</button>

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!