0

I am trying to insert the variable x to an existing html-tag.

The image-tag <img id="Img" src="IMG/.jpg"/> should get the variable x at the end of its id and its src:

        <script>
            var images = <?php echo (json_encode($files));?>
            for(x = 1;x < $images.length-2;x++){
                // <img id="Img"+x src="IMG/"+x+.jpg"/>
            }
        </script>
3
  • You seem to be missing the point of script tags, the HTML isn't echoed out as in PHP, you have to actually put it somewhere (and add quotes). and images != $images etc Commented May 16, 2014 at 22:16
  • 3
    Why don't you just write this all in php? Commented May 16, 2014 at 22:16
  • I've been trying to find a duplicate to use to close this, but everyone attempting anything similar has done the (very, very little) research needed to find a technique that generates the HTML and then only have specific problems with it. Commented May 16, 2014 at 22:20

2 Answers 2

1

First you want to get the actual id and src:

var path = document.getElementsByTagName("img")[0]; // That looks for all img-tags in your document and returns an array with all of them. I took the first one (number 0 in the array) - if it is not the first image, change that number.
var imgId = path.id;
var imgSrc = path.src;

You wanted to add the variable x to both of them:

var newId = imgId + x;
var newSrc = imgSrc + x;

Then you can write the new id and the new src in you image tag:

path.setAttribute("id", newId);
path.setAttribute("src", newSrc);

So your whole code should look like

<script>
    var images = <?php echo (json_encode($files));?>
    for(x = 1;x < $images.length-2;x++){
        //read the id and src
        var path = document.getElementsByTagName("img")[0];
        var imgId = path.id;
        var imgSrc = path.src;

        //change them
        var newId = imgId + x;
        var newSrc = imgSrc + x;

        //and write the new id and new src in the image-tag
        path.setAttribute("id", newId);
        path.setAttribute("src", newSrc);
    }
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

this here should work

<script>
        var images = <?php echo (json_encode($files));?>;
        for(x = 1;x < images.length-2;i++){
            document.write('<img id="Img"'+ x + ' src="IMG/"' + x + '.jpg"/>');
        }
</script>

im not sure but you may have to add some ' or " befor and after the php code

and i agree with @sublimeobject's comment

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.