skip to Main Content

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

Answers


  1. 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>
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search