406

How could I hide the 'Edit'-link after I press it? and also can I hide the "lorem ipsum" text when I press edit?

<script type="text/javascript">
function showStuff(id) {
  document.getElementById(id).style.display = 'block';
}
</script>


<td class="post">

  <a href="#" onclick="showStuff('answer1'); return false;">Edit</a>
  <span id="answer1" style="display: none;">
    <textarea rows="10" cols="115"></textarea>
  </span>

  Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum 
</td>
Sofyan Thayf
  • 1,322
  • 2
  • 14
  • 26
nortaga
  • 4,063
  • 2
  • 15
  • 4

15 Answers15

584

function showStuff(id, text, btn) {
    document.getElementById(id).style.display = 'block';
    // hide the lorem ipsum text
    document.getElementById(text).style.display = 'none';
    // hide the link
    btn.style.display = 'none';
}
<td class="post">

<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>
<span id="answer1" style="display: none;">
<textarea rows="10" cols="115"></textarea>
</span>

<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>
</td>
Jonathan
  • 2,700
  • 4
  • 23
  • 41
Sascha Galley
  • 15,711
  • 5
  • 37
  • 51
  • 6
    Why do you add `return false` in `onclick`? – Midas Jun 05 '11 at 13:06
  • 1
    Yes, I know. But I was wondering because it's not needed in case you use # as link. – Midas Jun 05 '11 at 13:24
  • 11
    It may be needed if you don't want to let JavaScript change the url from yourdomain.com/ to yourdomain.com/# ... furthermore, the scrolling of the window may jump, or any other non considered problem may occur. – Sascha Galley Sep 24 '11 at 00:30
  • 1
    I miss a link for testing that's why you can try here: konzertagentur-koerner.de/test But thanks for the good code – Timo Nov 05 '13 at 20:04
  • 2
    It's possible to use the visibility property instead of display unless you're targeting IE4 ;) – Eddie Oct 15 '15 at 20:43
  • 1
    Use the empty string in `style.display ` to use the default display, this should be usefull for `li`, `ul`, `table` etc etc – MUY Belgium Apr 26 '17 at 14:59
  • You shouldn't set display to 'block' — in some situations that will alter how the page is rendered. Instead see Ben Osborne's answer. – Abhi Beckert Jun 11 '18 at 23:47
123

You can also use this code to show/hide elements:

document.getElementById(id).style.visibility = "hidden";
document.getElementById(id).style.visibility = "visible";

NOTE

The difference between style.visibility and style.display is when using visibility:hidden unlike display:none, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.

See this link to see the differences.

informatik01
  • 16,038
  • 10
  • 74
  • 104
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
74

I would suggest this to hide elements (as others have suggested):

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

But to make elements visible, I'd suggest this (instead of display = 'block'):

document.getElementById(id).style.display = '';

The reason is that using display = 'block' is causing additional margin/whitespace next to the element being made visible in both IE (11) and Chrome (Version 43.0.2357.130 m) on the page I'm working on.

When you first load a page in Chrome, an element without a style attribute will appear like this in the DOM inspector:

element.style {
}

Hiding it using the standard JavaScript makes it this, as expected:

element.style {
  display: none;
}

Making it visible again using display = 'block' changes it to this:

element.style {
  display: block;
}

Which is not the same as it originally was. This could very well not make any difference in the majority of cases. But in some cases, it does introduce abnormalities.

Using display = '' does restore it to its original state in the DOM inspector, so it seems like the better approach.

Ben Osborne
  • 1,412
  • 13
  • 20
46

I would like to suggest you the JQuery option.

$("#item").toggle();
$("#item").hide();
$("#item").show();

For example:

$(document).ready(function(){
   $("#item").click(function(event){
     //Your actions here
   });
 });
Mc-
  • 3,968
  • 10
  • 38
  • 61
  • 77
    Sometimes JQuery isn't necessary; if this is the only thing you need to do on a page, the overhead of loading the library far outweighs the need to write concise JavaScript. – GlennG Oct 22 '14 at 13:24
  • 2
    It seems that hide() and jquery visibility methods in general are not a good option in terms of performance, as Addy Osmani explains here: https://speakerdeck.com/addyosmani/devtools-state-of-the-union-2015 – Emilio Mar 25 '15 at 11:03
  • 2
    while this might work the author isn't using jQuery so this doesn't seem like a relevant answer to the question. – A. Wentzel Oct 12 '18 at 01:11
34

you can use hidden property of element:

document.getElementById("test").hidden=true;
document.getElementById("test").hidden=false
Hadi Akbarzadeh
  • 750
  • 10
  • 18
  • Ooh! The reason I like this is because you may have different `display=""` values nowadays. – Andrew Jul 11 '19 at 18:10
  • Unfortunately, you can't use this in a CSS stylesheet, it seems. Thus, you'd either have to set it in the HTML or combine usage of `display: none;` etc. – Andrew Jul 11 '19 at 18:14
  • 7
    Caveat: this property is ignored if the CSS `display` property is set. – JasonWoof Sep 09 '19 at 16:05
  • 2
    If you want to set the `display` property to an element when it doesn't have the `hidden` attribute, target it like this: `.my-el:not([hidden]) { display: flex }` – gitaarik May 07 '20 at 16:52
  • it's not robust, https://css-tricks.com/the-hidden-attribute-is-visibly-weak/ – WeiChing 林煒清 Oct 16 '21 at 09:10
19

Vanilla JS for Classes and IDs

By ID

document.querySelector('#element-id').style.display = 'none';

By Class (Single element)

document.querySelector('.element-class-name').style.display = 'none';

By Class (Multiple elements)

for (const elem of document.querySelectorAll('.element-class-name')) {
    elem.style.display = 'none';
}
Chris Hayes
  • 11,505
  • 6
  • 33
  • 41
15

Though this question has been answered many times before, I thought I would add to it with a more complete and solid answer for future users. The main answer does solve the problem, but I believe it may be better to know/understand the some of various ways to show/hide things.

.

Changing display using css()

This is the way I used to do it until I found some of these other ways.

Javascript:

$("#element_to_hide").css("display", "none");  // To hide
$("#element_to_hide").css("display", "");  // To unhide

Pros:

  • Hides and unhides. That's about it.

Cons:

  • If you use the "display" attribute for something else, you will have to hardcode the value of what it was prior to hiding. So if you had "inline", you would have to do $("#element_to_hid").css("display", "inline"); otherwise it will default back to "block" or whatever else that it will be forced into.
  • Lends itself to typos.

Example: https://jsfiddle.net/4chd6e5r/1/

.

Changing display using addClass()/removeClass()

While setting up the example for this one, I actually ran into some flaws on this method that make it very very unreliable.

Css/Javascript:

.hidden {display:none}
$("#element_to_hide").addClass("hidden");  // To hide
$("#element_to_hide").removeClass("hidden");  // To unhide

Pros:

  • It hides....sometimes. Refer to p1 on the example.
  • After unhiding, it will return back to using the previous display value....sometimes. Refer to p1 on the example.
  • If you want to grab all hidden objects, you just need to do $(".hidden").

Cons:

  • Does not hide if the display value was set directly on the html. Refer to p2 on the example.
  • Does not hide if the display is set in javascript using css(). Refer to p3 on the example.
  • Slightly more code because you have to define a css attribute.

Example: https://jsfiddle.net/476oha8t/8/

.

Changing display using toggle()

Javascript:

$("element_to_hide").toggle();  // To hide and to unhide

Pros:

  • Always works.
  • Allows you to not have to worry about which state it was prior to switching. The obvious use for this is for a....toggle button.
  • Short and simple.

Cons:

  • If you need to know which state it is switching to in order to do something not directly related, you will have to add more code (an if statement) to find out which state it is in.
  • Similar to the previous con, if you want to run a set of instructions that contains the toggle() for the purpose of hiding, but you don't know if it is already hidden, you have to add a check (an if statement) to find out first and if it is already hidden, then skip. Refer to p1 of the example.
  • Related to the previous 2 cons, using toggle() for something that is specifically hiding or specifically showing, can be confusing to others reading your code as they do not know which way they will toggle.

Example: https://jsfiddle.net/cxcawkyk/1/

.

Changing display using hide()/show()

Javascript:

$("#element_to_hide").hide();  // To hide
$("#element_to_hide").show();  // To show

Pros:

  • Always works.
  • After unhiding, it will return back to using the previous display value.
  • You will always know which state you are swapping to so you:
    1. don't need to add if statements to check visibility before changing states if the state matters.
    2. won't confuse others reading your code as to which state you are switching to if, if the state matters.
  • Intuitive.

Cons:

  • If you want to imitate a toggle, you will have to check the state first and then switch to the other state. Use toggle() instead for these. Refer to p2 of the example.

Example: https://jsfiddle.net/k0ukhmfL/

.

Overall, I would say the best to be hide()/show() unless you specifically need it to be a toggle. I hope you found this information to be helpful.

Macainian
  • 362
  • 2
  • 10
  • 12
    Why did you decide to use jQuery in your answer? – Draex_ Apr 25 '16 at 16:58
  • 2
    @Draex_ Yeah I suppose he wanted javascript didn't he? To be honest, I was forced to move my answer to this thread because another thread was supposedly opinionated. I was just trying to give some helpful info to people, but there doesn't seem to be a place to do it. – Macainian Apr 25 '16 at 20:17
  • Also there is `$("#element_to_hide").hidden = true/false` – P i Jun 19 '20 at 10:27
12

You should think JS for behaviour, and CSS for visual candy as much as possible. By changing your HTML a bit :

<td class="post">
    <a class="p-edit-btn" href="#" onclick="showStuff(this.parentNode);return false;">Edit</a>
    <span id="answer1" class="post-answer">
       <textarea rows="10" cols="115"></textarea>
    </span>
    <span class="post-text" id="text1">Lorem ipsum ... </span>
</td>

You'll be able to switch from one view to the other simply using CSS rules :

td.post-editing > a.post-edit-btn,
td.post-editing > span.post-text,
td.post > span.post-answer
{
    display : none;
}

And JS code that switch between the two classes

<script type="text/javascript">
function showStuff(aPostTd) {
    aPostTd.className="post-editing";
}
</script>
sitifensys
  • 2,024
  • 16
  • 29
11

Just create hide and show methods yourself for all elements, as follows

Element.prototype.hide = function() {
    this.style.display = 'none';
}
Element.prototype.show = function() {
    this.style.display = '';
}

After this you can use the methods with the usual element identifiers like in these examples:

document.getElementByTagName('div')[3].hide();
document.getElementById('thing').show();

or:

<img src="removeME.png" onclick="this.hide()">
General Failure
  • 2,421
  • 4
  • 23
  • 49
Koos Jaspers
  • 111
  • 1
  • 2
6

If you are using it in a table use this :-

  <script type="text/javascript">
   function showStuff(id, text, btn) {
    document.getElementById(id).style.display = 'table-row';
    // hide the lorem ipsum text
    document.getElementById(text).style.display = 'none';
    // hide the link
    btn.style.display = 'none';
}
</script>


<td class="post">

<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>
<span id="answer1" style="display: none;">
<textarea rows="10" cols="115"></textarea>
</span>

<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>
</td>
phpdroid
  • 1,642
  • 1
  • 18
  • 36
5

I recommend Javascript, because its relatively fast and more malleable.

    <script>
function showStuff(id, text, btn) {
document.getElementById(id).style.display = 'block';
// hide the lorem ipsum text
document.getElementById(text).style.display = 'none';
// hide the link
btn.style.display = 'none';
}
</script>


<td class="post">

<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>
<span id="answer1" style="display: none;">
<textarea rows="10" cols="115"></textarea>
</span>

<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>
</td>
3

2022  ―  MINIMALIST WAY

Privileges: Avoid changing any style property that will uglify the code.

JS:

const hideElement = (e, ok) => e.setAttribute('hidden', !!ok);

CSS

[hidden="true"] { display: none }

Try

  • Show

    hideElement(myElement, false);
    
  • Hide

    hideElement(myElement, true);
    
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Ramy Hadid
  • 120
  • 6
  • This is nice. It shows a clean, surgical, best-practices approach to a decades-old task in a concise and cute presentation. – Garret Wilson Oct 25 '22 at 17:09
2
document.getElementById("an_id").hidden = true;   
vimuth
  • 5,064
  • 33
  • 79
  • 116
Ali Raji
  • 41
  • 2
1

(for those lured here by the "hide/show" in the title)

Either toggle inline style...

A one-liner to toggle display: none for some element:

element.style.display = (element.style.display) ? '' : 'none';

Example:

document.getElementById('button').addEventListener(
  'click', () => {
    for (const element of document.querySelectorAll('.content')) {
      element.style.display = (element.style.display) ? '' : 'none';
    }
  }
);
/* not required, only cosmetic */
#button {
  padding: 1em;
  background-color: steelblue;
  cursor: pointer;
}
<div id="button">click to toggle</div>
<div class="content">initially shown</div>
<div class="content" style="display: none">initially hidden</div>

... or toggle a css class

You could use element.classList.toggle() as follows:

document.querySelector('.button').addEventListener(
  'click', () => {
    document.querySelector('.content').classList.toggle('hidden');
  }
);
.hidden {
  display: none;
}


/* button styling is not required */

.button {
  text-decoration: underline;
  cursor: pointer;
}
<div class="button">click to toggle content</div>
<div class="content">some content</div>
djvg
  • 11,722
  • 5
  • 72
  • 103
  • Only works in specific case when element is initially shown – StefanBob Jun 28 '23 at 14:21
  • @StefanBob As far as I can see, this also works if the element is initially hidden. See updated code snippet. – djvg Jun 28 '23 at 14:59
  • Okay yes I think it's fine, my mistake, I was using this in an instance where I already had a CSS style for this element's id. This function was not overriding it, but when I put the style inline the html instead, this worked. Thanks, feel free to get rid of my edit sorry. – StefanBob Jun 28 '23 at 16:07
0

function showStuff(id, elem) {
    
    // Show/Hide element
    let tagEdit = document.getElementById(id);
    let newDisplay = (tagEdit.style.display == 'none'?'block':'none');
    tagEdit.style.display = newDisplay;
    
    // Change text of Edit element
    let newText = (elem.innerText == 'Edit'?'Close':'Edit');
    elem.innerText = newText;
    
}
<td class="post">

    <a href="#" onclick="showStuff('answer1',this); return false;">Edit</a>
    
    <span id="answer1" style="display: none;">
        <textarea rows="10" cols="115"></textarea>
    </span>

</td>
jmsmarcelo
  • 95
  • 2
  • 11