I have the following code which toggles the visibility of an item with a certain ID:
<div onClick="toggleViz()">Click this</div>
<div id="item1" style="display: none;">
<p>Item 1
</div>
<div id="item2" style="display: none;">
<p>Item 2
</div>
<script>
function toggleViz() {
var x = document.getElementById("item1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I’d like to pass the ID name of the item whose visibility I want to toggle to the function as a parameter, so I don’t have to write a new function for every item.
When I try this:
<div onClick="toggleViz(item1)">Click this 1</div>
<div onClick="toggleViz(item2)">Click this 2</div>
<div id="item1" style="display: none;">
<p>Item 1
</div>
<div id="item2" style="display: none;">
<p>Item 2
</div>
<script>
function toggleViz(id_name) {
var x = document.getElementById(id_name);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
I get: Uncaught TypeError: Cannot read properties of null (reading 'style')