Search code examples
javascripthtmlgetelementbyidgetelementsbyclassname

Why won't JavaScript object display more than once?


I am trying to create a list of objects in JS and create them in classes. I need to be able to call them throughout the website by a simple variable. Many will be called more than once.

When I create the object, as an ID, I can call it in the HTML, but it only displays once and I can't duplicate it if I need to. If I create the object in a class format, it won't display at all.

Where am I going wrong?

Or is this not the best way to accomplish this?

var myObj, x;
myObj = {"session1":"NAVIGATING AND NETWORKING THE CONFERENCE"};
x = myObj.session1;
document.getElementsByClassName("session1").innerHTML = x;
<div class="session1"></div>
<br>
<div class="session1"></div>


Solution

  • You need to loop over the elements that document.getElementsByClassName("session1"); returns, it's an array (you need a loop to set the innerHTML of all those elements). Like,

    var myObj, x;
    myObj = {"session1":"NAVIGATING AND NETWORKING THE CONFERENCE"};
    x = myObj.session1;
    elems = document.getElementsByClassName("session1");
    for (var i = 0; i < elems.length; i++) {
        elems[i].innerHTML = x;
    }
    <div class="session1"></div>
    <br />
    <div class="session1"></div>