admin管理员组

文章数量:1335371

I've tried a lot of ways to fix this problem but can't figure it out.

My problem is that I try to select all <img> by doing

document.getElementsByTagName("img")

and then add .src=text[x] to it like this:

document.getElementsByTagName("img").src=text[x];

Well that doesn't work. I've also tried to use this:

var r = document.getElementsByTagName("img");
r.src=text[x];

Again, nothing. If I use this code(immg is the ID all the <img> have):

document.getElementById('immg').src=text[x];

It does work but only on the first object since it's only searching for one element with ID immg and not all of them.

My full code:

first function

function generateChar()
{
    var text = [
        "img/Water1.png",
        "img/Water2.png",
        "img/Water3.png",
        "img/Water4.png",
        "img/Water5.png",
        "img/Water6.png",
    ];
    var size = text.length;
    var x = Math.floor(size*Math.random());
    //document.getElementsByTagName("img").src=text[x];
    //document.getElementById('immg').src=text[x];
    var r = document.getElementsByTagName("img");

    r.src=text[x];
    //console.log(r);
}

the other useful code:

var nbDiv = 50;
for(var i = 0; i < nbDiv; i++){
    var div = document.createElement('div');
    var imgg = document.createElement('img');

    div.id = "d"+i ;
    imgg.id = "immg";
    imgg.className = "iimg";
    div.className = "movement timeSpan";
    document.querySelector('body').appendChild(div);
    div.appendChild(imgg);
}

and generateChar() is called under the for()

So what I would want to achieve is giving all the img a random picture(which works I only need to select the right items).

All solutions are wele.

I've tried a lot of ways to fix this problem but can't figure it out.

My problem is that I try to select all <img> by doing

document.getElementsByTagName("img")

and then add .src=text[x] to it like this:

document.getElementsByTagName("img").src=text[x];

Well that doesn't work. I've also tried to use this:

var r = document.getElementsByTagName("img");
r.src=text[x];

Again, nothing. If I use this code(immg is the ID all the <img> have):

document.getElementById('immg').src=text[x];

It does work but only on the first object since it's only searching for one element with ID immg and not all of them.

My full code:

first function

function generateChar()
{
    var text = [
        "img/Water1.png",
        "img/Water2.png",
        "img/Water3.png",
        "img/Water4.png",
        "img/Water5.png",
        "img/Water6.png",
    ];
    var size = text.length;
    var x = Math.floor(size*Math.random());
    //document.getElementsByTagName("img").src=text[x];
    //document.getElementById('immg').src=text[x];
    var r = document.getElementsByTagName("img");

    r.src=text[x];
    //console.log(r);
}

the other useful code:

var nbDiv = 50;
for(var i = 0; i < nbDiv; i++){
    var div = document.createElement('div');
    var imgg = document.createElement('img');

    div.id = "d"+i ;
    imgg.id = "immg";
    imgg.className = "iimg";
    div.className = "movement timeSpan";
    document.querySelector('body').appendChild(div);
    div.appendChild(imgg);
}

and generateChar() is called under the for()

So what I would want to achieve is giving all the img a random picture(which works I only need to select the right items).

All solutions are wele.

Share Improve this question edited Dec 16, 2022 at 22:31 Jason Aller 3,65228 gold badges41 silver badges39 bronze badges asked Oct 17, 2018 at 10:24 Ramon de VriesRamon de Vries 1,3428 silver badges20 bronze badges 6
  • 1 document.getElementsByTagName give node list instead of single node. document.getElementsByTagName("img")[0].src will work – Umair Abid Commented Oct 17, 2018 at 10:25
  • 2 You are using .src on an array which won't work. – Jerodev Commented Oct 17, 2018 at 10:26
  • Take a look here – Federico klez Culloca Commented Oct 17, 2018 at 10:26
  • Possible duplicate of JS: iterating over result of getElementsByClassName using Array.forEach – lumio Commented Oct 17, 2018 at 10:26
  • can you share the html? – brk Commented Oct 17, 2018 at 10:27
 |  Show 1 more ment

3 Answers 3

Reset to default 5

document.getElementsByTagName() returns an HTMLCollection, which is an iterable list of elements.

This is what you should do:

let images = document.getElementsByTagName('img')

for (image of images) {
    x = Math.floor(Math.random() * text.length) // pick a random image URL
    image.src = text[x] // set the src to that URL
}

Also, I see you are saying:

immg is the ID all the <img> have

It is wrong to use the same ID on multiple elements. Never do this! IDs should be unique. That's also why if you use getElementById it only returns the first element found, because it assumes that the ID you are providing is unique for that element.

You should use classes instead, like this:

<img class='immg'>

Try this code to add a random/list src to img tag:

    // Random
    var items = ["http://placehold.jp/9062aa/cccc00/150x100.png", "http://placehold.jp/3fb4e9/cccc00/150x100.png", "http://placehold.jp/6fc063/cccc00/150x100.png", "http://placehold.jp/d94949/cccc00/150x100.png", "http://placehold.jp/f8951e/cccc00/150x100.png","http://placehold.jp/7a564a/cccc00/150x100.png"];

    $(".random-img").each(function (index) {

        var img = items[Math.floor(Math.random() * items.length)];
        $(this).attr('src', img);

    });
    
    // Listed
        var items2 = ["http://placehold.jp/9062aa/cccc00/150x100.png", "http://placehold.jp/3fb4e9/cccc00/150x100.png", "http://placehold.jp/6fc063/cccc00/150x100.png", "http://placehold.jp/d94949/cccc00/150x100.png", "http://placehold.jp/f8951e/cccc00/150x100.png","http://placehold.jp/7a564a/cccc00/150x100.png"];

    $(".list-img").each(function (index) {

        var img2 = items2[index % items2.length];
        $(this).attr('src', img2);

    });
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <h1>Random images from array</h1>
    <img class="random-img" />
    <img class="random-img" />
    <img class="random-img" />
    <img class="random-img" />
    <img class="random-img" />
    <img class="random-img" />
    
    
    <h1>Listed images from array</h1>
    <img class="list-img" />
    <img class="list-img" />
    <img class="list-img" />
    <img class="list-img" />
    <img class="list-img" />
    <img class="list-img" />

Just get a random image text from the array and use that in the loop.

function getRandomImage(img) {
  var images = [
    "img/Water1.png",
    "img/Water2.png",
    "img/Water3.png",
    "img/Water4.png",
    "img/Water5.png",
    "img/Water6.png",
  ];
  var rand = images[Math.floor(Math.random() * images.length)];
  return rand
}

(function() {
  var nbDiv = 50;
  for (var i = 0; i < nbDiv; i++) {
    var div = document.createElement('div');
    var imgg = document.createElement('img');
    div.id = "d" + i;
    div.className = "movement timeSpan";
    imgg.id = "immg" + i;
    imgg.className = "iimg";
    randomImg = getRandomImage();
    imgg.src = randomImg;
    imgg.alt = randomImg;
    div.appendChild(imgg);
   // console.log(imgg);
    document.getElementsByTagName('body')[0].appendChild(div);
  }
}())
.iimg {
  border: 1px solid lime;
  width: 100px;
  height: 100px;
  display:block;
}

A jQuery version of same thing

function getRandomImage(img) {
  var images = [
    "img/Water1.png",
    "img/Water2.png",
    "img/Water3.png",
    "img/Water4.png",
    "img/Water5.png",
    "img/Water6.png",
  ];
  var rand = images[Math.floor(Math.random() * images.length)];
  return rand
}

(function() {
  var nbDiv = 50;
  for (var i = 0; i < nbDiv; i++) {
    randomImg = getRandomImage();
    var div = $('<div/>')
      .addClass("movement timeSpan")
      .attr('id', "d" + i);
    var imgg = $('<img/>').addClass("iimg")
      .attr('id', "immg" + i)
      .attr('alt', randomImg)
      .attr('src', randomImg);
    imgg.appendTo(div);
    $('body').append(div);
  }
}())
.iimg {
  border: 1px solid lime;
  width: 100px;
  height: 100px;
  display: block;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

本文标签: javascriptSelect all img tags and give them a srcStack Overflow