EN
JavaScript - hide and show element using placeholder
0
points
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>