5

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

0

3 Answers 3

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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.

2 Comments

I think you meant to use Array.prototype.slice.apply
Yeah, fixed. Thanks. Works great now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.