How to get all images from img tag and background

2019-03-16 09:26发布

问题:

I want to get all images from HTML page. want to get all images from <img> tag source or get images from element background from HTML contents.

How can I get?

回答1:

You can just loop over all elements on the page and check if it's an image or it has some image background. The biggest problem of this solution is that it's very slow (however its performance could 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));
    }
});


回答2:

for getting images from all the image tags i think you could simply iterate over a image tag


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

for getting all of the background images you will have to look for the background property in all the elements.


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


回答3:

For gettings images from img tag, use this

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);}
});


回答4:

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

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