Artex
Artex

Reputation: 27

Uncaught TypeError: is not a function in Chrome

So I'm writing a userscript for a website and I'm encountering this error Uncaught TypeError: is not a function It doesn't occur in Firefox, but does in Chrome. I've spent the last hour debugging with no success.

I've provided the relevant snippets below to reproduce the error in chrome. The script is supposed to find the button containing the text 'Download' and return the href.

function getSubmissionSource(){
  var controlBar = document.getElementsByClassName("button submission rounded");
  for (var button of controlBar) { //errors here
    var link = button.getElementsByTagName("a")[0];
    if (link !== undefined && link.textContent == "Download") {
      return link.href;
    }
  }
}
console.log(getSubmissionSource());
<div id="test"">
  <span class="button submission rounded">
    <a href="/view/18251152/" class="prev dotted">Older</a>
  </span>
  <span class="button submission rounded">
    <a href="">-Remove from Favorites</a>
  </span>
  <span class="button submission rounded">
    <a href="">Download</a>
  </span>
  <span class="button submission rounded">
    <a href="">Note user</a></span>
  <span class="button submission rounded">
    <a href="/view/18385008/">Newer</a>
    </span>
</div>

Upvotes: 1

Views: 3000

Answers (2)

Robert
Robert

Reputation: 20286

There is no of operator in JavaScript you need to change

for (var button of controlBar) {

to

for (var button in controlBar) {

Upvotes: 1

Rayon
Rayon

Reputation: 36609

You need to use for loop to iterate through nodelist

function getSubmissionSource(){
  var controlBar = document.getElementsByClassName("button submission rounded");
  for (var i=0,iLen=controlBar.length;i<iLen; i++) { //errors here
    var link = controlBar[i].getElementsByTagName("a")[0];
    if (link !== undefined && link.textContent == "Download") {
      return link.href;
    }
  }
}
console.log(getSubmissionSource());
<div id="test"">
  <span class="button submission rounded">
    <a href="/view/18251152/" class="prev dotted">Older</a>
  </span>
  <span class="button submission rounded">
    <a href="">-Remove from Favorites</a>
  </span>
  <span class="button submission rounded">
    <a href="">Download</a>
  </span>
  <span class="button submission rounded">
    <a href="">Note user</a></span>
  <span class="button submission rounded">
    <a href="/view/18385008/">Newer</a>
    </span>
</div>

Upvotes: 3

Related Questions