javascriptgetelementbyidappendchildsetattribute

JS Need help to add href on img


i'm using Innova Content Builder to record my webpage. It's contains a module called saveimage.php which transforms binary images to jpg files. This works perfectly.

Now, i would like to encapsulate these img whith href links, but it doesn't works.

Here is my code :

parent.document.getElementById('img-" . $count . "').setAttribute('src','" . $urlpath . $image . "');
parent.document.getElementById('img-" . $count . "').setAttribute('alt','".$image."');
var myLink = document.createElement('a');
myLink.setAttribute('href','http://www.google.fr');
parent.document.getElementById('img-" . $count . "').appendChild(myLink);

This code is placed into a body onload function. I think it's a parentality problem.

Can you help me ? Thanks !


Solution

  • Use this:

    <script>
        parent.document.getElementById('img-" . $count . "').setAttribute('src','" . $urlpath . $image . "');
        parent.document.getElementById('img-" . $count . "').setAttribute('alt','".$image."');
    var myLink = document.createElement('a');
    myLink.setAttribute('href','http://www.google.fr');
        parent.document.getElementById('img-" . $count . "').parentNode.insertBefore(myLink, parent.document.getElementById('img-" . $count . "'));
        myLink.appendChild(parent.document.getElementById('img-" . $count . "'));
    </script>