How to get all images from an img tag and background images from an HTML page using jQuery?

I want to get all the images from an HTML page. Do you want to get all the images from the source of the <img> or to get images from the background of the element from the HTML content.

How can I get?

+4
source share
4 answers

You can simply iterate over all the elements on the page and check if this image has or has some background image. The biggest problem with this solution is that it is very slow (however, its performance can be improved in several ways). Here is the code:

 $('*').each(function(){ var backImg; if ($(this).is('img')) { console.log($(this).attr('src')); } else { backImg = $(this).css('background-image'); if (backImg != 'none') console.log(backImg.substring(4, backImg.length-1)); } }); 
+10
source

to get images from all image tags, i think you could just iterate over the image tag

 $('img').each(function(){ alert($(this).attr('src')); });
$('img').each(function(){ alert($(this).attr('src')); }); 

to get all background images you have to look for the background property in all elements.

 $('*').each(function(){ alert($(this).css('background-image')); }); 
+4
source

For images of images from the img tag use

 var images = []; $("img").each(function(){ if(this.src){images.push(this.src);} }); $('*').each(function(){ var bg = $(this).css('background-image'); if( bg && bg != 'none'){images.push(bg);} }); 
+2
source

Select all the tags on the page with $('img') To find all the background images from the HTML content, you need to go through each element, check if it has the CSS property of the background image, and if so, write down the value of this property . I think it will look something like this:

 $('*').each(function() { if ($(this).css('background-image') != '') //record however you're recording it }); 
0
source

Source: https://habr.com/ru/post/1388087/


All Articles