Why doesn't getElementById(theID)
work with innerHTML
?
Works:
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
</script>
Doesn't work:
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
<script>
function myFunction() {
document.getElementById(theID).innerHTML = "Paragraph changed!";
}
</script>
getElementById(theID)
works with style.display
:
<style>
h2 {
display: inline;
}
.openclose {
cursor: pointer; /* or: hand; */
margin-left: 1em;
}
.image {
display: none;
}
</style>
<script>
function openClose(theID) {
if (document.getElementById(theID).style.display == "initial") {
document.getElementById(theID).style.display = "none"
document.getElementsByTagName("span")[0].innerHTML = "[+]"
} else {
document.getElementById(theID).style.display = "initial"
document.getElementsByTagName("span")[0].innerHTML = "[–]"
}
}</script>
<h2>Heading - 1st</h2><span class="openclose" onClick="openClose('a1')">[+]</span>
<br /><br /><img id="a1" class="image" src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAgMAAADXB5lNAAAAC
VBMVEX///8AAAD/AADAyZ2wAAAAg0lEQVQ4y73QsQnEMBBE0bFByeVqQlW4BAWa5KpxKZcciK3SA
1IBg4z9E7EvWMTixRJVvQUaShf6kBtQ+ng9SOz4RPxQWF04YraZkHjsWqA158a6CBW7ZsmJ9CTEg
LDhGzF+GvG3gbN1IJsOrQNn0gMJBkCzB8iYNdjQ5usDOMMCvNYFYQmUU1ZqYuIAAAAASUVORK5CY
II=">
<br /><br />
<h2>Heading - 2nd</h2><span class="openclose" onClick="openClose('a2')">[+]</span>
<img id="a2" class="image" src="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
As tested here.
Additionally is it possible to ambiguate getElementsByTagName("span")[0]
to something like getElementsByTagName(theTagName)[theIndexNumber]
?
theID
coming from? – Evan Knowles May 19 '15 at 7:30