Nathan Martin
Nathan Martin

Reputation: 305

How do I locate a specific line of code from a website and then display it on an html file using javascript?

So basically I'm programming a website for someone and I want it to display his current fan count which will be copied directly from his Soundcloud account. Here is the coding I'm using right now: (if it helps to find the code I'm trying to locate. Here is a link to his Soundcloud. I'm trying to locate the "Follower" number count. https://soundcloud.com/gammatoid-official)

<p id="Text"></p>
<script src="https://soundcloud.com/gammatoid-official" type="text/html">
</script>
<script>
var fanSel = document.getElementsByClassName("infoStats__value sc-font-tabular-light").innerHTML;
document.getElementById("Text").innerHTML = fanSel;
</script>

It keeps giving me "undefined" as a result but I can't figure out what needs to be changed.

Upvotes: 1

Views: 886

Answers (2)

Pedro Castilho
Pedro Castilho

Reputation: 10532

The way you are currently trying to do this won't work, because you can't load data from other websites without getting explicit permission from them through Cross-Origin Resource Sharing (CORS).

You should use Soundcloud's API for this. Even if you successfully scrape this data from their website, your code will need to change whenever they change their website, and that will be a hassle to maintain, while their API should stay relatively stable.

You can request the follower count of a given user using the /users endpoint. It will give you a JSON object which has, among other properties, follower_count.

Upvotes: 1

serdar.sanri
serdar.sanri

Reputation: 2228

You can't load a page like that as script and get contents out of it. You may take a look ajax calls. Still crossdomain policy needs to be considered and below is not tested but you may get the point.

$.ajax({
   url : 'https://soundcloud.com/gammatoid-official',
   type : 'GET', 
   success: function(resultHTML){
      var $html = $(resultHTML);
      var fansel = $html.find('.infoStats__value .sc-font-tabular-light').text();
      $("Text").innerHTML = fanSel;
   }
})

Upvotes: 0

Related Questions