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.
window.addEventListener('load', function() {
document.getElementById('btn').addEventListener('click', function(e) {
var style = document.getElementsByTagName('ol')[0].style;
style.display = (style.display == 'none') ? 'block' : 'none';
}, true);
}, true);
To toggle display, you can use the display CSS attribute set to either block for displayed as a block element, or none for not displayed at all.
Well you would want to use getElementsByTagName instead of getElementByTagName, note its plural. This will then return an array.
var arrayOfElements = document.getElementsByTagName('ol');
var aSingleElement = document.getElementsByTagName('ol')[0];
aSingleElement .style.display('none');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With