Jorge Rodríguez
Jorge Rodríguez

Reputation: 427

JQuery Selectors ul li

I'm trying to get all the src of images in a unordered list, here's the HTML:

<ul id="slideshow">
        <li>
            <h2 rel="yummy fruit!">Fruit</h2>
            <img src="images/fruit.jpg" alt="fruit" />
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </li>
        <li>
            <h2>Vegetables</h2>
            <img src="images/vegetable.jpg" alt="vegetables" />
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </li>
        <li>
            <h2>Bread</h2>
            <img src="images/bread.jpg" alt="bread" />
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </li>
    </ul>

for that I'm using this function:

$(document).ready(function () {
    $("#btn1").click(function () {
            var $images = $('#slideshow img').attr('src');;
            console.log($images);
    });
});

The problem is that I only get the fist src (images/fruit.jpg), then I need to randomly order that images, any help?

Upvotes: 2

Views: 47

Answers (2)

David Thomas
David Thomas

Reputation: 253308

One approach is the following:

// gets an array of each of the <img> elements'
// src property:
var imgSources = $('img').map(function() {
  return this.src;
}).get();

// iterates over each of the <img> elements, and updates
// its src property:
$('img').prop('src', function() {
  // index: is a random number between 0 and the last index of
  // the array:
  var index = Math.floor(Math.random() * imgSources.length),
  // source: one of the array elements:
    source = imgSources[index];
  // removing the used array-element, to ensure all elements are used,
  // and there are no duplicates:
  imgSources.splice(index, 1);

  // returning the found-element as the new src:
  return source;
});

var imgSources = $('img').map(function() {
  return this.src;
}).get();

$('img').prop('src', function() {
  var index = Math.floor(Math.random() * imgSources.length),
    source = imgSources[index];
  imgSources.splice(index, 1);
  return source;
});
h2 + img {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="slideshow">
  <li>
    <h2 rel="yummy fruit!">Fruit</h2>
    <img src="http://lorempixel.com/100/100/nature/Image%201" alt="fruit" />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li>
  <li>
    <h2>Vegetables</h2>
    <img src="http://lorempixel.com/100/100/nightlife/Image%202" alt="vegetables" />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li>
  <li>
    <h2>Bread</h2>
    <img src="http://lorempixel.com/100/100/people/Image%203" alt="bread" />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li>
</ul>

It's just occurred to me that this could be easily implemented in native JavaScript, and almost as simply:

// retrieving a NodeList of all <img> elements, using
// Array.prototype.slice, with Function.prototype.call(),
// to convert that NodeList to an Array:
var images = Array.prototype.slice.call(document.getElementsByTagName('img'), 0),
  // Array.prototype.map used to create a new Array,
  // storing the src properties of each of the <img> elements:
  imgSources = images.map(function(img) {
    // img: the current <img> from the array of <img>s over
    // which we're iterating:
    return img.src;
  });

// iterating over each of the <img> elements:
images.forEach(function(img) {
  // img: again the current <img> element from the array
  // of images.

  // creating a random number between 0 and one less-than
  // (using Math.floor()) the length of the array:
  var index = Math.floor(Math.random() * imgSources.length),
    // caching an element from the imgSources array:
    newSource = imgSources[index];

  // removing the array-element, at the random index point,
  // from the array:
  imgSources.splice(index, 1);

  // updating the src property of the current <img>:
  img.src = newSource;
});

var images = Array.prototype.slice.call(document.getElementsByTagName('img'), 0),
  imgSources = images.map(function(el) {
    return el.src;
  });

images.forEach(function(img) {
  var index = Math.floor(Math.random() * imgSources.length),
    newSource = imgSources[index];
  imgSources.splice(index, 1);
  img.src = newSource;
});
h2 + img {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="slideshow">
  <li>
    <h2 rel="yummy fruit!">Fruit</h2>
    <img src="http://lorempixel.com/100/100/nature/Image%201" alt="fruit" />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li>
  <li>
    <h2>Vegetables</h2>
    <img src="http://lorempixel.com/100/100/nightlife/Image%202" alt="vegetables" />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li>
  <li>
    <h2>Bread</h2>
    <img src="http://lorempixel.com/100/100/people/Image%203" alt="bread" />
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </li>
</ul>

References:

Upvotes: 3

DLeh
DLeh

Reputation: 24395

You could loop through each img to get the sources like this:

$(document).ready(function () {
    $("#btn1").click(function () {
        var images = new Array();
        $('#slideshow img').each(function (index, element){
            images.push(element.attr('src'));
        });
        console.log(images);
    });
});

This gets all the sources into a list. If you'd like to randomly order the list, there are plenty of resources on how to do this in javascript, here's an example: https://stackoverflow.com/a/2450976/526704

Upvotes: 0

Related Questions