简体   繁体   中英

How to change HTML tags by using JavaScript

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>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM