Nazım Gel
Nazım Gel

Reputation: 3

Output text before <img> tag

This my code:

 <script type="text/javascript" language="javascript">
        var youtubeimgsrc = document.getElementById('youtubeimg').src;
      document.write(youtubeimgsrc); 
</script>

  <img src="https://yt3.ggpht.com/-xf7anhq4eRo/AAAAAAAAAAI/AAAAAAAAAAA/wQIFalodFjE/s88-c-k-no/photo.jpg" id="youtubeimg">

Jsfiddle: http://jsfiddle.net/vrnsydLb/

I have to put script code before img but it is not working. I tried onload, it worked but all content was removed in page. Is there any way for work?

Upvotes: 0

Views: 170

Answers (2)

ThisIsMatt
ThisIsMatt

Reputation: 126

<html>
<head>
    <script>
        function toRun() {

            var src = document.getElementById('bar').getAttribute('src'),
                text = document.createTextNode(src),
                container = document.getElementById("mesaj1");

            container.insertBefore(text, container.childNodes[0]);
        }

        window.onload = toRun;
    </script>
</head>
<body>
<div id="mesaj1"><img src="https://yt3.ggpht.com/-xf7anhq4eRo/AAAAAAAAAAI/AAAAAAAAAAA/wQIFalodFjE/s88-c-k-no/photo.jpg" id="bar"></div>
</body>

</html>

I would also suggest possible hiding the "mesaj1" div using css, and then showing it at the end of the toRun() function, to prevent the image from showing up without the text right before onload is called.

Upvotes: 0

Ben Aston
Ben Aston

Reputation: 55729

Change the following:

<html>
<head>
    <script>
    function toRun() {

        var src = document.getElementById('bar').getAttribute('src');
        document.getElementById('foo').textContent = src;
    }

    window.onload = toRun;
    </script>
</head>
<body>
    <img src="https://yt3.ggpht.com/-xf7anhq4eRo/AAAAAAAAAAI/AAAAAAAAAAA/wQIFalodFjE/s88-c-k-no/photo.jpg" id="bar">
    <div id="foo"></div> ##must be closed##
</body>

</html>

Upvotes: 1

Related Questions