Jquey for-Loop - Function returns "Cannot set Property 'href' of Undefined"

Asked

Viewed 33 times

2

I’m trying to create a function that searches all the links of a div and shorten them:

function encurtarUrl(){

        var conteudoPronto = document.getElementById("saida"); // armazena a DIV com id "saida"
        var numeroAProntos = conteudoPronto.getElementsByTagName("a").length; // conta o numero de 

        for (c=0; c < numeroAProntos; c++){

            $.getJSON( "http://is.gd/create.php?callback=?", {
                url: conteudoPronto.getElementsByTagName("a")[c].href,
                format: "json"
            }).done(function( data ) {
                urlEncurtada = data.shorturl;
                document.getElementById("saida").getElementsByTagName("a")[c].href = urlEncurtada; // subistitui o link antigo pelo encurtado
            });
        }

    }

But on the line document.getElementById("saida").getElementsByTagName("span")[c].href = urlEncurtada; He returns: Cannot set Property 'href' of Undefined

HTML code:

<div id="saida"><br>
  *Título Noticia 1*<br>
  Texto noticia 1<a href="http://www.google.com">www.google.com</a><br>
  <br>
  *Titulo noticia 2*<br>
  Texto noticia 2<a href="http://www.facebook.com">www.facebook.com</a><br>
  <br>
  *Titulo Noticia 3*<br>
  Texto noticia 3<a href="http://www.twitter.com">www.twitter.com</a><br>
</div>
  • At the time of writing the code here I made a mistake, there on the line "Document.getElementById("output"). getelementsbytagname("span")[c]. href = urlEncurtada;" the element it looks for is "a" and not "span";

  • can post a snippet of HTML?

  • Hello Wesley! Take a look at this other question I pointed out. I think you’re missing the c for having asynchronous code. If you can’t solve it says here.

  • 1

    @Sergio Consegui resolver! Thanks.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.