LoginSignup
0
0

HTML上に画像があるか探す

Posted at

開いたページから画像が存在するか探す方法のメモ。
HTML上に画像があるか探します。
下のコードは多少変えていますが、MDNのコードです。

const imageList = document.images;

for (let i = 0; i < imageList.length; i++) {
  if (imageList[i].src == "apple.jpg") {
    // 画像が存在した時の処理
  }
}

上記コードで処理できるそうですが、私の環境ですと、うまく画像を探すことができませんでした。
いろいろ試したところ、絶対パスを指定することで動作でしました。

if (imageList[i].src == '指定のURL/img/apple.jpg')

ただ上記の書き方ですと、使用できる場面が限定的になるので、実装上ではindexOfを使用するのがベターかなと思いました。

if (imageList[i].src.indexOf('apple.jpg') != -1)

参考

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0