Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 221
Gary Avatar asked Jul 27 '11 09:07

Gary


2 Answers

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;
}
like image 113
Jacob Relkin Avatar answered Oct 21 '22 18:10

Jacob Relkin


var images = document.getElementsByTagName('IMG');
for (var i = 0; i < images.length; ++i) {
    if (images[i].src == "pic.gif")
        images[i].style.display = 'none';
}
like image 2
lazyhammer Avatar answered Oct 21 '22 20:10

lazyhammer