Languages
[Edit]
EN

JavaScript - hide and show element using placeholder

0 points
Created by:
ArcadeParade
666

In this article, we would like to show you how to hide and show element using a placeholder in JavaScript.

Practical example

In this example, we create a placeholder, which is HTML <script> tag - with that solution, we don't take up additional space inside DOM. Then we use replaceChild() method to hide/show the element by replacing it with the placeholder.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    p.my-elelement {
        background: orange;
    }
    
  </style>
</head>
<body>
  <button onclick="showElement()">Show element</button>
  <button onclick="hideElement()">Hide element</button>
  <div>
    <p>Some text here ...</p>
    <script id="placeholder" type="text/placeholder"></script>
    <p>Some text here ...</p>
  </div>
  <script>
    
    var placeholder = document.querySelector('#placeholder');
    
    var element = document.createElement('p');
    
    element.className = 'my-elelement';
    element.innerText = 'Some additional text here ...';
    
    var container = placeholder.parentNode;

    function showElement() {
          if (element.parentNode == null) {
            container.replaceChild(element, placeholder);
        }
    }

    function hideElement() {
        if (placeholder.parentNode == null) {
            container.replaceChild(placeholder, element);
        }
    }
    
  </script>
</body>
</html>

See also

  1. JavaScript - hide and show element on click event 

Alternative titles

  1. JavaScript - hide or show element using HTML script placeholder element
  2. JavaScript - hide and show element on click event using placeholder
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join