Reputation: 259
I'm working on my first JavaScript game and I want to display certain attributes inside of < p> tags. The ID of each < p> tag will be equal to "show-" and the name of the attribute (see example below for the attribute "name").
But I'm having trouble getting the syntax right for getElementById. Any suggestions?
<p id="show-name"></p>
<script>
name = "Bob";
function display(attribute) {
putItHere = "'show-"+attribute+"'"
document.getElementById(putItHere).innerHTML = attribute;
}
display(name);
</script>
Upvotes: 0
Views: 8520
Reputation: 5676
Your attribute is Bob
. So putItHere = "'show-"+attribute+"'"
is equivalent to: putItHere = "'show-"+"Bob"+"'"
, which makes no sense.
You should get the following error Uncaught TypeError: Cannot set property 'innerHTML' of null
.
This should do:
function display(attrname, val){
document.querySelector('#show-'+attrname).innerText=val;
}
display("name","Bob");
Here is the Fiddle to play with.
Upvotes: 0
Reputation: 1780
You need to target the right element. Currently you are targeting 'show-Bob' and not 'show-name' what your trying to do. So first generate the id, from the key name
and then assign a value to that element.
var name = "Bob";
function display(key, value) {
var putItHere = "show-"+ key;
document.getElementById(putItHere).innerHTML = value;
}
display('name', name);
note
keep in mind that IDs should be unique within the document
However, other way to do that is to target all elements with a specific tag, for instance
<div data-id="name"></div>
<div data-id="name"></div>
<div data-id="name"></div>
<script type="text/javascript">
var name = "Bob";
function display(key, value) {
var putItHere = "show-"+ key;
var elements = document.querySelectorAll('div[data-id="'+key+'"]');
for(var eid in elements) {
var element = elements[eid];
element.innerHTML = value;
}
}
display('name', name);
</script>
note
that that this doesn't work in IE7 and below.
Upvotes: 2