Grab image address, jquery

Asked

Viewed 627 times

1

Hello, good morning!

I’d like to get the value SRC of the IMG tag, using js/jquery. In case it would be https://i.imgur.com/1gIalgU.jpg

<html>
    <head>
        <title>hello</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

        <script>
        function get(){
            //????
            //alert(img);
            alert('a');
        }
        </script>
    </head>

    <body onload="get()">
        <img src="https://i.imgur.com/1gIalgU.jpg" width="100" height="100">
    </body>
</html>

it is possible?

1 answer

3


Do so:

<html>
    <head>
        <title>hello</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

        <script>
        function get(){
            var linkImagem = $('#imagem').attr('src');
            alert(linkImagem);
        }
        </script>
    </head>

    <body onload="get()">
        <img src="https://i.imgur.com/1gIalgU.jpg" width="100" height="100" id="imagem">
    </body>
</html>
  • Perfect! Nat, just one more thing, I would like to replace this variable?

  • Something like this: var a = linkImagem.replace("i.imgur.com", "facebook");

  • Always return this error > Uncaught Typeerror: Cannot read Property 'replace' of Undefined

  • @Luanpedro I put it like this in jsFiddle and it worked: var Link2 = linkImagem.replace('i.imgur.com', 'facebook.com'); Are you doing it right on the console? Or the page itself that is returning this? See: https://jsfiddle.net/ndelavi/s3u1fLdp/

  • https://pastebin.com/svvNbd6K

  • I’m putting it like this

  • I changed a few things in your code: https://jsfiddle.net/ndelavi/s3u1fLdp/5/

  • Thank you very much! <3

  • 1

    For nothing, just to explain, was giving error because you were trying to run get() before the page was fully loaded, so jquery was not able to get the link value, always bringing 'Undefined'. Calling the get after Document.ready, forces the page to be loaded first before calling the get(). Nice that it helped. See you soon.

Show 4 more comments

Browser other questions tagged

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