0

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>
2
  • 1
    the id should be show-Bob no? Commented May 7, 2015 at 13:29
  • Change to display("name"). Commented May 7, 2015 at 13:29

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And keep in mind that IDs should be unique within the document.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.