CSS:
ol{display: block;} // display: ""; throws an error in the console(FF)
HTML:
<!DOCTYPE html>
<html>
<head><script type="text/javascript">!js is here!</script>
<body>
<h2>Title</h2>
<input type="button" id="btn" value="expand" />
<ol>
<li>Value 1</li>
<li>Value 1</li>
<li>Value 1</li>
</ol>
</body>
</html>
Javascript: // trying to just hide the element for now
window.onload = function() {
function expand() {
var ol = document.getElementByTagName('ol');
ol.style.display('none');
}
function init() {
var btn = document.getElementById('btn');
btn.addEventListener('click', expand, false);
}
}
I’ve been searching high and low for something similar, everything I found used an additional library(utility.js, jquery etc.), but for learning purposes I want to do this in pure JS.
Every source online cites element.className = "newClass";. I tried that by making a class .hide{display: none;} and .show{display: "";}, but it doesn’t seem to do anything. Then I switched to manipulating the style (element.style.display("none");), but that doesn’t seem to work either.
As your JavaScript appears before the elements are loaded into the DOM, you need to wait until the window has loaded (or document is ready, not shown in this snippet) before adding the event listeners to the button.
To toggle display, you can use the
displayCSS attribute set to eitherblockfor displayed as a block element, ornonefor not displayed at all.