Gary
Gary

Reputation: 747

jQuery find image by 'src' attribute - plain javascript

By my own admission I have become quite a competent user of jQuery without much knowledge of the javascript that goes on behind it.

Just lately I have attempted to find a compromise when weighing up whether it is worth importing the jQuery framework for relatively small tasks. And as a learning exercise to attempt to a least think about how it could be achieved without jQuery.

I'm currently working on something where jQuery is not an option. (Large organisation with practices set in stone).

I am able to select an image using it's source with jQuery however could anyone explain how to do this in plain javaScript.

$('img[src*="pic.gif"]').hide();

Many thanks Gary

Upvotes: 5

Views: 10338

Answers (3)

Jacob Relkin
Jacob Relkin

Reputation: 163238

Like so:

function findImagesByRegexp(regexp, parentNode) {
   var images = Array.prototype.slice.call((parentNode || document).getElementsByTagName('img'));
   var length = images.length;
   var ret = [];
   for(var i = 0; i < length; ++i) {
      if(images[i].src.search(regexp) != -1) {
         ret.push(images[i]);
      }
   }
   return ret;
}

Upvotes: 5

bjornd
bjornd

Reputation: 22943

Just select all images on page and filter their src with regexp or string functions:

var imgs = Array.prototype.slice.apply(document.getElementsByTagName('img')),
    resultImgs = [];
for (var i = 0; i < imgs.length; i++) {
    if (imgs[i].src.indexOf('img.gif') !== -1) {
        resultImgs.push(imgs[i]);
    }
}

Take attention to Array.prototype.slice.apply. It converts HTMLCollection which is returned by getElementsByTagName to regular array. This will improve speed of your script hundreds times.

Upvotes: 2

lazyhammer
lazyhammer

Reputation: 1228

var images = document.getElementsByTagName('IMG');
for (var i = 0; i < images.length; ++i) {
    if (images[i].src == "pic.gif")
        images[i].style.display = 'none';
}

Upvotes: 2

Related Questions