[javascript] Show/hide 'div' using JavaScript

For a website I'm doing, I want to load one div, and hide another, then have two buttons that will toggle views between the div using JavaScript.

This is my current code

_x000D_
_x000D_
function replaceContentInContainer(target, source) {_x000D_
  document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;_x000D_
}_x000D_
_x000D_
function replaceContentInOtherContainer(replace_target, source) {_x000D_
  document.getElementById(replace_target).innerHTML = document.getElementById(source).innerHTML;_x000D_
}
_x000D_
<html>_x000D_
<button onClick="replaceContentInContainer('target', 'replace_target')">View Portfolio</button>_x000D_
<button onClick="replaceContentInOtherContainer('replace_target', 'target')">View Results</button>_x000D_
_x000D_
<div>_x000D_
  <span id="target">div1</span>_x000D_
</div>_x000D_
_x000D_
<div style="display:none">_x000D_
  <span id="replace_target">div2</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The second function that replaces div2 is not working, but the first one is.

This question is related to javascript html onclick innerhtml

The answer is


Just Simple Function Need To implement Show/hide 'div' using JavaScript

<a id="morelink" class="link-more" style="font-weight: bold; display: block;" onclick="this.style.display='none'; document.getElementById('states').style.display='block'; return false;">READ MORE</a>


<div id="states" style="display: block; line-height: 1.6em;">
 text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here  
    <a class="link-less" style="font-weight: bold;" onclick="document.getElementById('morelink').style.display='inline-block'; document.getElementById('states').style.display='none'; return false;">LESS INFORMATION</a>
    </div>

And the Purescript answer, for people using Halogen:

import CSS (display, displayNone)
import Halogen.HTML as HH
import Halogen.HTML.CSS as CSS

render state = 
  HH.div [ CSS.style $ display displayNone ] [ HH.text "Hi there!" ]

If you "inspect element", you'll see something like:

<div style="display: none">Hi there!</div>

but nothing will actually display on your screen, as expected.


Just Simple Set the style attribute of ID:

To Show the hidden div

<div id="xyz" style="display:none">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='block';  // to hide

To hide the shown div

<div id="xyz">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='none';  // to display

I found this question and recently I was implementing some UIs using Vue.js so this can be a good alternative.

First your code is not hiding target when you click on View Profile. You are overriding the content target with div2.

_x000D_
_x000D_
let multiple = new Vue({_x000D_
  el: "#multiple",_x000D_
  data: {_x000D_
    items: [{_x000D_
        id: 0,_x000D_
        name: 'View Profile',_x000D_
        desc: 'Show profile',_x000D_
        show: false,_x000D_
      },_x000D_
      {_x000D_
        id: 1,_x000D_
        name: 'View Results',_x000D_
        desc: 'Show results',_x000D_
        show: false,_x000D_
      },_x000D_
    ],_x000D_
    selected: '',_x000D_
    shown: false,_x000D_
  },_x000D_
  methods: {_x000D_
    showItem: function(item) {_x000D_
      if (this.selected && this.selected.id === item.id) {_x000D_
        item.show = item.show && this.shown ? false : !item.show;_x000D_
      } else {_x000D_
        item.show = (this.selected.show || !item.show) && this.shown ? true : !this.shown;_x000D_
      }_x000D_
      this.shown = item.show;_x000D_
      this.selected = item;_x000D_
    },_x000D_
  },_x000D_
});
_x000D_
<div id="multiple">_x000D_
  <button type="button" v-for="item in items" v-on:click="showItem(item)">{{item.name}}</button>_x000D_
_x000D_
  <div class="" v-if="shown">: {{selected.desc}}</div>_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
_x000D_
_x000D_
_x000D_


Instead your both functions use toggle function with following body

this[target].parentNode.style.display = 'none'
this[source].parentNode.style.display = 'block'

_x000D_
_x000D_
function toggle(target, source) {
  this[target].parentNode.style.display = 'none'
  this[source].parentNode.style.display = 'block'
}
_x000D_
<button onClick="toggle('target', 'replace_target')">View Portfolio</button>
<button onClick="toggle('replace_target', 'target')">View Results</button>

<div>
  <span id="target">div1</span>
</div>

<div style="display:none">
  <span id="replace_target">div2</span>
</div>
_x000D_
_x000D_
_x000D_


You can also use the jQuery JavaScript framework:

To Hide Div Block

$(".divIDClass").hide();

To show Div Block

$(".divIDClass").show();

Set your HTML as

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }

<script type="text/javascript">
    function hide(){
        document.getElementById('id').hidden = true;
    }
    function show(){
        document.getElementById('id').hidden = false;
    }
</script>

A simple example with a Button to scroll up. It will only scroll if the javascript is active, which is an event listening to the scroll type.

_x000D_
_x000D_
document.getElementById('btn').style.display='none'

window.addEventListener('scroll', (event) => {
    console.log(scrollY)
    document.getElementById('btn').style.display='inline'
})
_x000D_
a
long<br>
text<br>
comes<br>
long<br>
text<br>
again

<button id=btn class = 'btn btn-primary' onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>
_x000D_
_x000D_
_x000D_

Live in action here


I found this plain JavaScript code very handy!

#<script type="text/javascript">
    function toggle_visibility(id) 
    {
        var e = document.getElementById(id);
        if ( e.style.display == 'block' )
            e.style.display = 'none';
        else
            e.style.display = 'block';
    }
</script>

You can simply manipulate the style of the div in question...

document.getElementById('target').style.display = 'none';

Using style:

<style type="text/css">
   .hidden {
        display: none;
   {
   .visible {
        display: block;
   }
</style>

Using an event handler in JavaScript is better than the onclick="" attribute in HTML:

<button id="RenderPortfolio_Btn">View Portfolio</button>
<button id="RenderResults_Btn">View Results</button>

<div class="visible" id="portfolio">
    <span>div1</span>
</div>

<div class"hidden" id="results">
    <span>div2</span>
</div>

JavaScript:

<script type="text/javascript">

    var portfolioDiv = document.getElementById('portfolio');
    var resultsDiv = document.getElementById('results');

    var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
    var resultsBtn = document.getElementById('RenderResults_Btn');

    portfolioBtn.onclick = function() {
        resultsDiv.setAttribute('class', 'hidden');
        portfolioDiv.setAttribute('class', 'visible');
    };

    resultsBtn.onclick = function() {
        portfolioDiv.setAttribute('class', 'hidden');
        resultsDiv.setAttribute('class', 'visible');
    };

</script>

jQuery may help you to manipulate DOM elements easy!


You can easily achieve this with the use of jQuery .toggle().

$("#btnDisplay").click(function() {
  $("#div1").toggle();
  $("#div2").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
  First Div
</div>
<div id="div2" style="display: none;">
  Second Div
</div>
<button id="btnDisplay">Display</button>

You can Hide/Show Div using Js function. sample below

<script>
    function showDivAttid(){

        if(Your Condition) {

            document.getElementById("attid").style.display = 'inline';
        }
        else
        {
            document.getElementById("attid").style.display = 'none';
        }
    }

</script>

HTML -

<div  id="attid" style="display:none;">Show/Hide this text</div>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to onclick

How to use onClick with divs in React.js React prevent event bubbling in nested components on click React onClick function fires on render Run php function on button click Passing string parameter in JavaScript function Simple if else onclick then do? How to call a php script/function on a html button click Change Button color onClick RecyclerView onClick javascript get x and y coordinates on mouse click

Examples related to innerhtml

React.js: Set innerHTML vs dangerouslySetInnerHTML Angular 2 - innerHTML styling How do I clear inner HTML Show/hide 'div' using JavaScript How to get the innerHTML of selectable jquery element? Cannot set property 'innerHTML' of null Add/remove HTML inside div using JavaScript Javascript - Replace html using innerHTML Add inline style using Javascript It says that TypeError: document.getElementById(...) is null