Reputation: 3
I have two searches of a JSON file producing results on two separate parts of the page in two separate divs. The results are produced by for loops, and many hidden divs are created in each of the two results divs, which are displayed by onclick. The id's in div #1 are as "a"+i, where i is the for loop counter. Div #2 is similar with the hidden id's being "aa"+i. Must not have duplicate ID's. The document.getElementById in the function unhyde() is null, if I pass the hidden div's id to display it as thus:
function allWriter() {
var i = "2"; // to simulate one for loop iteration
var theid = "a"+i;
var out = '<div onclick="unhyde('+theid+')">John Smith</div>';
out +='<div id="'+theid+'\" style="display: none;">Read This</div>';
document.getElementById('b').innerHTML = out;
}
function unhyde (theid) {
document.getElementById(theid).style.display="block";
<body>
<div onclick="allWriter()">start</div>
<div id="b"></div>
</body>
Why? But the following works, but the "a" or "aa" must be hardcoded in the unhyde() function, and I don't want that:
function allWriter() {
var i = "2"; // to simulate one for loop iteration
var out = '<div onclick=\"unhyde('+i+')">John Smith</div>';
out +='<div id="a'+i+'" style="display: none;">Read This</div>';
document.getElementById('b').innerHTML = out;
}
function unhyde (i) {
document.getElementById('a'+i).style.display="block";
}
<body>
<div onclick="allWriter()">start</div>
<div id="b"></div>
</body>
How can I do this by passing the whole id as a variable and use the same unhyde() function regardless of the id? And why the difference in these two examples? I'd rather not use JQuery, but will only if there's no other way.
Upvotes: 0
Views: 1164
Reputation: 816334
If you look at the generated code for the first example, you see that it generates
onlick="unhyde(a2)"
I.e. it tries to pass the variable a2
to the function. Coincidentally, it exists. It refers to the DOM element with ID a2
. However, since the value already is a DOM element, you cannot pass it to document.getElementById
, getElementById
expects a string.
The problem does not exist in the second case because the generated code is unhyde(2)
, i.e. you are passing the number 2
to the function and "a" + 2
will result in the string "a2"
, which getElementById
happily accepts.
To fix the first example you simply have to add quotes, so that you are passing a string instead (unhyde("a2")
):
var out = '<div onclick="unhyde(\''+theid+'\')">John Smith</div>';
This is actually a great example why dynamically creating HTML is not a very good approach. A cleaner solution would be to create DOM elements and directly bind the event handler.
Upvotes: 1