-1

On click I can hide my div element with display:none but can't get it back with display:inline when button is clicked

document.getElementById("red").onclick = function (){
    document.getElementById("red").style.display = "none";
}
document.getElementById("back").onclick = function () {
    document.getElementsById("red").style.display = "inline";
}
6
  • 6
    getElementsById ...? is that a typo ...? Commented Mar 13, 2017 at 19:08
  • getElementById instead of getElementsById... Commented Mar 13, 2017 at 19:08
  • you can use visibility:hidden instead.
    – bhansa
    Commented Mar 13, 2017 at 19:09
  • 1
    Step one, check the console: Uncaught TypeError: document.getElementsById is not a function
    – Jonathan
    Commented Mar 13, 2017 at 19:09
  • 1
    well, as you have not shared any HTML , minimal example here:: jsfiddle.net/31wajbg7/1 works fine... Commented Mar 13, 2017 at 19:17

4 Answers 4

0

Hi your script has typo error. getElementsById is having Elements instead of Element. Alway use Console for error messages it will help you alot :). Cheers !!! Your script should look like this .

 document.getElementById("red").onclick = function (){
    document.getElementById("red").style.display = "none";
       }
document.getElementById("back").onclick = function () {
    document.getElementById("red").style.display = "inline";
}
0

Example: display:none to display:inline toggle.

document.getElementById("red").onclick = function (){
    document.getElementById("red").style.display = "none";
}
document.getElementById("back").onclick = function () {
    document.getElementById("red").style.display = "inline";
}
#red 
{
color:#fff;
background:red;
padding:8px 20px;
}
<div id="red">RED (Click me)</div>

<button id="back">Back</button>

You can always see the errors in the console and figure out the solution.

0

I would advise you to use a class for styling and also use Element.addEventListener() for the events.

var red = document.getElementById('red')
var back = document.getElementById('back')
red.addEventListener('click', function() {
    this.classList.add('hidden')
})
back.addEventListener('click', function() {
    red.classList.remove('hidden')
})

https://jsfiddle.net/cnzabf1a/

Documentation on:

0

If your're using flex using 'inline-flex' may be better:

document.getElementById("red").style.display = "inline-flex";

Not the answer you're looking for? Browse other questions tagged or ask your own question.