How to get all images from img tag and background

2019-03-16 08:56发布

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?

4条回答
放我归山
2楼-- · 2019-03-16 09:20

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);}
});
查看更多
趁早两清
3楼-- · 2019-03-16 09:25

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));
    }
});
查看更多
太酷不给撩
4楼-- · 2019-03-16 09:30

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
});
查看更多
女痞
5楼-- · 2019-03-16 09:45

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'));
});
查看更多
登录 后发表回答