How to convert this document.write to innerHTML?

68 Views Asked by At

I'm using this script to output the total number of posts.

<script>
function mbhTotalCount(json) {
  var totalCount = parseInt(json.feed.openSearch$totalResults.$t, 10);
document.write (totalCount);
}
</script>
<span class='count'>
  <script src="/feeds/posts/default?alt=json-in-script&callback=mbhTotalCount"></script>
</span>

How can we change this to alternative form?

2

There are 2 best solutions below

0
Davi Amaral On BEST ANSWER

I'm not sure if I understood correctly, but maybe you can try this:

1 - Give the span tag an id to make it easy to reference it in JavaScript

2 - Modify the JavaScript function to change the innerHTML of the span instead of using document.write:

<script>
function mbhTotalCount(json) {
  var totalCount = parseInt(json.feed.openSearch$totalResults.$t, 10);
  document.getElementById("postCount").innerHTML = totalCount;
}
</script>

<span class="count" id="postCount">
  <script src="/feeds/posts/default?alt=json-in-script&callback=mbhTotalCount"></script>
</span>

This way, you're updating the inner content of the span element directly, which is a more modern and reliable method than document.write.

0
Barmar On

Simply assign the variable to the innerText of the span.

<script>
function mbhTotalCount(json) {
  var totalCount = parseInt(json.feed.openSearch$totalResults.$t, 10);
  document.getElementById("count").innerText = totalCount;
}
</script>
<span class='count'>
  <script src="/feeds/posts/default?alt=json-in-script&callback=mbhTotalCount"></script>
</span>