开发者

document.getElementsByTagName('img') , how to only get png images?

开发者 https://www.devze.com 2023-04-10 13:51 出处:网络
I am trying to only get images with the png attribute开发者_JS百科 from the dom, does anyone know how to this?There is no safe way of doing this. The browser does not expose anywhere what type of imag

I am trying to only get images with the png attribute开发者_JS百科 from the dom, does anyone know how to this?


There is no safe way of doing this. The browser does not expose anywhere what type of image has been loaded. Moreover, you can't even guarantee that the image URL will have the correct file extension, because http://example.com/some/image is a quite valid URL.

You can get an approximation using the "attribute contains" CSS selector with querySelectorAll with browsers that support it:

var pngs = document.querySelectorAll('img[src*=".png"]');

That finds all img elements with .png somewhere in their src attribute. Note that this is vulnerable both to false positives and to false negatives.

This method will not work in IE 7 or below.


To iterate over the images and return those with a src property ending in .png:

var images = document.images;
var pngs = [];
for (var i=0, iLen=images.length; i<iLen; i++){
  if (/\.png$/i.test(images[i].src))
    pngs.push(images[i]);
}

pngs is an array of images whose src ends in .png and will work in nearly every browser that ever supported scripting.

If you want something that uses querySelectorAll if available and a simple loop over images if not, then the following should suit (per lonesomeday's ansewr):

function getPngs() {

  if (document.querySelectorAll) {
    return document.querySelectorAll('img[src*=".png"]');
  }

  var images = document.images;
  var pngs = [];
  var re = /\.png$/i; 
  for (var i=0, iLen=images.length; i<iLen; i++){
    if (re.test(images[i].src)) {
      pngs.push(images[i]);
    }
  }
  return pngs;
}

You might get back a NodeList or an array, but if all you want to do is iterate over it then that's ok. Otherwise you'll need to convert the result of the qSA fork to an array, which is a couple more lines of code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号