Javascript get all images

Javascript how to get all img

Solution 2: I will suggest that you create a function for getting images and also call the same function after ajax execution. Edit Pass an or string present in document or returned ajax data to limit the scope of the function Solution 3: This is how I solved it: Inside AJAX response.

JQuery / Javascript — get all images that are loaded

This is the code I’m using to get all loaded images :

$("img").on('load', function() < console.log('Image Loaded'); >).each(function() < if(this.complete)< //$(this).trigger('load'); var img = $(this).attr('src'); console.log(img); >>); 

but it’s not working with those that are loaded with ajax afterwards, so I tried:

$(document).on('load', 'img', function()< console.log('Image Loaded'); >).each(function() < if(this.complete)< //$(this).trigger('load'); var img = $(this).attr('src'); console.log(img); >>); 

but it’s not doing anything, what would be the correct way? I need to manipulate the parent divs of each image that is freshly loaded, so getting just all images period on every ajax load would be overkill and not elegant

$(document).on('load', 'img', function()< console.log('Image Loaded'); var parent = $(this).parent(); //or .parents('div') or .closest('div'), etc.. //do something with parent >); 

I will suggest that you create a function for getting images and also call the same function after ajax execution .

Pass an id or class string present in document or returned ajax data to limit the scope of the function

function getImages(id) < $('#' + id).find("img").on('load', function() < console.log('Image Loaded'); >).each(function() < if(this.complete) < //$(this).trigger('load'); var img = $(this).attr('src'); console.log(img); >>); > getImages('outsideAjax'); // call during normal execution. outsideAjax is an id within your html document but not in the returned ajax data $.ajax(< // ajax settings >).done(function() < // post ajax code // append returned data to document getImages('insideAjax'); // recall after successful ajax execution and appending of returned data. 'insideAjax' is an id inside your return ajax data >).fail(function(jqXHR, textStatus, errorThrown) < // report error >); 
 Inside AJAX response.

I think it’s self explanatory, works perfectly!

In the checkPic functuion I find this element by the src and get the parent elements and so on.

I need to extract all images src from an html string using regex, The basic idea is that we add a class to the container div then we can use body tag also. But I recommend to make it more granular. Pick the

How to find all img src attributes from sfpg (Single File PHP Gallery)

I am trying to create a user script in Greasemonkey to iterate over all the imgs in the following gallery to download the actual images from the thumbnails.

Читайте также:  Laravel php artisan error

The difference between thumbnail and image is the value of the url query parameter; so we have to change cmd=thumb into cmd=image . Which is pretty easy.

so first I am trying get all the img tags in a var and then trying to iterate over all the tags and in each iteration using string replace to change the thumb into image to get the actual image.

But this method is not retrieving any img. In every other page I can find all imgs , except this page.

Would be helpful if anyone can tell me why it is happening?

In the following snippet , first I am trying to see all the img tags in console, but its returning only baseURI, not the internal imgs. I have also checked the tags.count is returning 1 , instead of 3, as there are three images on this page. Unless I am able to find the imgs, I can’t do the next part , i.e., changing the URL and autodownload. That code is ready with me and working on other websites.

// ==UserScript== // @name Unnamed Script 629250 // @version 1 // @match http://sye.dk/sfpg/demo/index.php?sfpg=RnJ1aXRzL09yYW5nZSBGcnVpdHMvKipkN2UwYWI2MTRkZGU2MTBiYjliMzEzM2M2ZDUzODE3MTY0OWU4ZWI3YjU0MzcwMTU2ODIxN2YxMTA2NWFiOWEw // @grant none // ==/UserScript==(function() < 'use strict'; var tags = document.getElementsByTagName('img'); for(var i=0;i>)();

Document Inspector Screenshot on Google Chrome

The images are lazy-loaded — they’re not included in the HTML immediately on page load. The lazy solution would be to add a small setTimeout before trying to select the img s.

Another issue is that there are more than just the three img s there — better to select only the ones in the thumbnail view , with .thumbbox img . Try something like this instead:

// ==UserScript== // @name sveimages // @version 1 // @match http://sye.dk/sfpg/demo/index.php?sfpg=RnJ1aXRzL09yYW5nZSBGcnVpdHMvKipkN2UwYWI2MTRkZGU2MTBiYjliMzEzM2M2ZDUzODE3MTY0OWU4ZWI3YjU0MzcwMTU2ODIxN2YxMTA2NWFiOWEw // @grant none // ==/UserScript== setTimeout(() => < const fullImageURLs = Array.from( document.querySelectorAll('.thumbbox img'), img =>img.src.replace('cmd=thumb', 'cmd=image') ); console.log(fullImageURLs); >, 100); 
Array(3) 0:"http://sye.dk/sfpg/demo/index.php?cmd=image&sfpg=RnJ1aXRzL09yYW5nZSBGcnVpdHMvKkNsZW1lbnRpbmVzLmpwZyowZmYzZmJlOTBlZjI3MjRhMzIwYzEzY2UxNzgzMGFlYTg3ZjM2OTg0NjZhOTM3NzllNWNhNTY1Y2FkNjczNmYy" 1:"http://sye.dk/sfpg/demo/index.php?cmd=image&sfpg=RnJ1aXRzL09yYW5nZSBGcnVpdHMvKkZ1bm55IEZydWl0LmpwZypjMmY5ZGI2ZmEzZDA1Y2UxNGE1NmQ1OGVmODA1YjhmNTU1ODU2MmZmNzZhM2RmNDUxMmFmNGRiODE5YTg1YTc1" 2:"http://sye.dk/sfpg/demo/index.php?cmd=image&sfpg=RnJ1aXRzL09yYW5nZSBGcnVpdHMvKk9yYW5nZXMuanBnKmQ2ZDlkMDc1MDYxMWI4OTA5NDk1NGE1NzEzMmE3ZDg5YWYzNDllNjQ4YTgwMzhkODg5YzhjZTViMzZlNjUwNTM" length:3 

Javascript — Select all img tags and give them a src, Select all img tags and give them a src · 1. document.getElementsByTagName give node list instead of single node. · 2. You are using . · Take a

Phantomjs getting all img elements

I have the following code in an exercise I’ve made for myself:

var imgs = page.evaluate(function() < return document.images; >); for (var i in imgs)

but I only get multiple «undefined» messages.

When I try getAttribute(‘src’), I get:» ‘undefined’ is not a function. » error message.

Читайте также:  Php large file uploads

I’ve verified the page has img elements with src attributes.

I solved this by as suggested here by:

See this question for more information.

How to load all the images from one of my folder into my web page, var dir = «Src/themes/base/images/»; var fileextension = «.png»; $.ajax(< //This will retrieve the contents of the folder if the folder is configured as '

Источник

JavaScript — get src of all images on web page

user4838

In this article, we would like to show you how to get src of all images on web page using JavaScript.

const findImages = () => < const urls = []; for (const image of document.images) < urls.push(image.src); >return urls; >;
const findImages = () => < const images = document.querySelectorAll('img'); const urls = []; for (const image of images) < urls.push(image.src); >return urls; >

Practical examples

1. Using document.images property

In this example, we use document.images property to get a collection of the images in the current HTML document. Then we iterate the collection using for. of loop to get src of all images.

// ONLINE-RUNNER:browser;         

2. Using querySelectorAll() method

In this example, we use querySelectorAll() method to get the collection of all images on the web page. Then using for loop we create array of src properties of all images.

// ONLINE-RUNNER:browser;         

Note:

The findImages() function needs to be executed after window load event or at the end of the script to make sure that all items are loaded before the function execution.

See also

References

Источник

Get All Images in DOM (including background)

Quite useful if you are writing an browser extension or something.

To get all the images in DOM there are actually three places we are going to look at: element, background-image CSS property and, . Yes, every iframe hides a magical kingdom.

If you only want to get images in , two options for you to choose:

You can either search the DOM for img tag:

function getImgs (doc)  return Array.from(doc.getElementsByTagName('img')) .map(img => ( src: img.currentSrc, // img.src if you want the origin width: img.naturalWidth, height: img.naturalHeight >)) > getImgs(document) 
function getImgs (doc)  return Array.from(doc.images) .map(img => ( src: img.currentSrc, // img.src if you want the origin width: img.naturalWidth, height: img.naturalHeight >)) > getImgs(document) 

For background-image , we need to check every node in DOM:

function getBgImgs (doc)  const srcChecker = /url\(\s*?['"]?\s*?(\S+?)\s*?["']?\s*?\)/i return Array.from( Array.from(doc.querySelectorAll('*')) .reduce((collection, node) =>  let prop = window.getComputedStyle(node, null) .getPropertyValue('background-image') // match `url(. )` let match = srcChecker.exec(prop) if (match)  collection.add(match[1]) > return collection >, new Set()) ) > getBgImgs(document) 

We can’t simply get the width and height of a background image. If you need them, you have to load it.

Since the images you get in DOM are most likely already in the browser cache, the loading process should be fairly quick.

function loadImg (src, timeout = 500)  var imgPromise = new Promise((resolve, reject) =>  let img = new Image() img.onload = () =>  resolve( src: src, width: img.naturalWidth, height: img.naturalHeight >) > img.onerror = reject img.src = src >) var timer = new Promise((resolve, reject) =>  setTimeout(reject, timeout) >) return Promise.race([imgPromise, timer]) > function loadImgAll (imgList, timeout = 500)  return new Promise((resolve, reject) =>  Promise.all( imgList .map(src => loadImg(src, timeout)) .map(p => p.catch(e => false)) ).then(results => resolve(results.filter(r => r))) >) > loadImgAll(getBgImgs(document)).then(imgs => console.log(imgs)) 

Just recursively search in all iframes

function searchIframes (doc)  var imgList = [] doc.querySelectorAll('iframe') .forEach(iframe =>  try  iframeDoc = iframe.contentDocument || iframe.contentWindow.document imgList = imgList.concat(getImgs(iframeDoc) || []) // or getBgImgs(iframeDoc) imgList = imgList.concat(searchIframes(iframeDoc) || []) > catch (e)  // simply ignore errors (e.g. cross-origin) > >) return imgList > searchIframes(document) 

Can be used out of the box. It was made when I was writing a Chrome Extension.

function getImgAll (doc)  return new Promise((resolve, reject) =>  loadImgAll(Array.from(searchDOM(doc))) .then(resolve, reject) >) function searchDOM (doc)  const srcChecker = /url\(\s*?['"]?\s*?(\S+?)\s*?["']?\s*?\)/i return Array.from(doc.querySelectorAll('*')) .reduce((collection, node) =>  // bg src let prop = window.getComputedStyle(node, null) .getPropertyValue('background-image') // match `url(. )` let match = srcChecker.exec(prop) if (match)  collection.add(match[1]) > if (/^img$/i.test(node.tagName))  // src from img tag collection.add(node.src) > else if (/^frame$/i.test(node.tagName))  // iframe try  searchDOM(node.contentDocument || node.contentWindow.document) .forEach(img =>  if (img)  collection.add(img) > >) > catch (e) > > return collection >, new Set()) > function loadImg (src, timeout = 500)  var imgPromise = new Promise((resolve, reject) =>  let img = new Image() img.onload = () =>  resolve( src: src, width: img.naturalWidth, height: img.naturalHeight >) > img.onerror = reject img.src = src >) var timer = new Promise((resolve, reject) =>  setTimeout(reject, timeout) >) return Promise.race([imgPromise, timer]) > function loadImgAll (imgList, timeout = 500)  return new Promise((resolve, reject) =>  Promise.all( imgList .map(src => loadImg(src, timeout)) .map(p => p.catch(e => false)) ).then(results => resolve(results.filter(r => r))) >) > > getImgAll(document).then(list => console.log(list)) 

Источник

Оцените статью