Reputation: 171
<p id = "a" onclick = "doThis()">ABCD</p>
function doThis() {
output = document.getElementById("a");
alert(output.innerHTML);
//alert should say ABCD//
}
The above code works fine. Now, my problem is, I have multiple id's, and I want to change them dynamically. I tried doing this by adding parameters to doThis(); it works fine, but when I set up temp = document.getElementById(stringId) and attempt to alert the innerHTML, the console gives me an error saying it cannot read innerHTML, and that temp is null. How come it doesn't work like the above?
<p id = "a" onclick = "doThis(a)">ABCD</p>
<p id = "b" onclick = "doThis(b)">EFGH</p>
function doThis(x) {
theId = '"' + x + '"';
output = document.getElementById(theId);
//here I used alert to test it. Both output and it's innerHTML is "null". Why isn't the innerHTML ABCD or EFGH?//
Upvotes: 1
Views: 57
Reputation: 51100
Because the name of the Id isn't "a"
it's a
Try something like this instead:
theId = x;
Upvotes: 1
Reputation: 51165
You can simply change your on click to "doThis('a')"
and then your code will work. Right now you are not passing in a string, which is what getElementById
is expecting.
function doThis(x) {
output = document.getElementById(x);
console.log(output.innerHTML)
}
<p id="a" onclick="doThis('a')">ABCD</p>
<p id="b" onclick="doThis('b')">EFGH</p>
Here is a snippet showing what you are passing in in your question:
function doThis(x) {
console.log(typeof(x));
}
<p id = "a" onclick = "doThis(a)">ABCD</p>
<p id = "b" onclick = "doThis(b)">EFGH</p>
As you can see, you are passing an object, not a string.
Upvotes: 2
Reputation: 4757
You need to pass the id in quotes
doThis('a')
function doThis(x) {
alert(document.getElementById(x).innerHTML);
}
<p id="a" onclick="doThis('a')">ABCD</p>
<p id="b" onclick="doThis('b')">EFGH</p>
Upvotes: 0
Reputation: 1635
<p id = "a" onclick = "doThis('a')">ABCD</p>
<p id = "b" onclick = "doThis('b')">EFGH</p>
<script type="text/javascript">
function doThis(x) {
theId = '"' + x + '"';
output = document.getElementById(theId);
</script>
Upvotes: 1