0

I'm creating a game, I'm mostly displaying data like so:

document.getElementById("p1_TickStat").innerHTML = NumFix(1 * master.p1_Boost);

This works well for singular stats, but I want to be able to show the same variable stat on multiple sections of the page.

I've tried:

document.getElementsByClassName("p1_TickStat").innerHTML = NumFix(1 * master.p1_Boost);

With:

<b class="p1_TickStat">x</b>

But that doesn't work. I understand .getElementsByClassName() uses arrays instead, but for displaying a single stat I'm not sure how to write it. Thanks.

edit: Also tried something like this but not having it.

var elements = document.getElementsByClassName("p1_TickStat");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = NumFix(1 * master.p1_Boost);
}
  • 2
    `getElementsByClassName` (note the plural `getElements` in the name) returns a collection of elements. You'll need to loop through and modify each element within it. – Jonathan Lonowski Nov 22 '15 at 17:20
  • @JonathanLonowski why don't you write that as an answer? – Shomz Nov 22 '15 at 17:21
  • For your [edit](https://stackoverflow.com/revisions/33857718/2): jQuery defines the [`.html()`](http://api.jquery.com/html/) method for its collections to set the `innerHTML` of all matched elements – `$("p1_TickStat").html(NumFix(1 * master.p1_Boost));` – Jonathan Lonowski Nov 22 '15 at 17:25
  • Sorry new to the site, i removed that jQuery from my main post with something else I tried. Now I tried the jQuery you posted but it's not having it. $(".p1_TickStat").each(function(){ var update; update = $("p1_TickStat").html(NumFix(1 * master.p1_Boost)); }); – Tom Vanlaer-McCanna Nov 22 '15 at 17:31
  • For your latest edit, can you expand on the snippet? Does it find the elements you expect it to – `elements.length > 0`? You may checkout the possible reasons and solutions described in [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Jonathan Lonowski Nov 22 '15 at 17:31
  • 1
    $(".p1_TickStat").html(NumFix(1*master.p1_Boost)); – Zorgatone Nov 22 '15 at 17:33
  • The html method works directly on every element of the matched set – Zorgatone Nov 22 '15 at 17:34
  • Ooo it seems to be working now with the snippet I edited in to the main post. Thanks for your help Jonathan. – Tom Vanlaer-McCanna Nov 22 '15 at 17:34

0 Answers0