简体   繁体   中英

JS how to get all img src tags

I want to get the SRC from every <IMG> in twitter.

let n = document.getElementsByTagName("img");

for(tip of n){
    console.log(tip.src);
}

and it works for other pages, but it doesn't for twitter. Finally I did this;

let n = document.getElementsByTagName("img");

function example(){
    for(tip of n){
        if(tip.src == "https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg"){
            tip.src = "https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg";
        }
    }
}

setInterval(example, 100);

With setInterval it works, also, twitter loads stuff dynamically so with setInterval I can get all those new results. (How I could do that without using setInterval?)

Also, for some weird reason, the picture doesn't change. It doesn't update.

Update:

function example(){
let n = document.getElementsByTagName("div");
    for(tip of n){
        console.log(tip.style['background-image']);

        if(tip.style['background-image'] == 'url("https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg")'){
            tip.style['background-image']= 'url("https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg")';
        }
    }
}

setInterval(example, 10000);

Now it works perfectly, but how could I get the new data without using setInterval eeeeeeevery time and only call to the function when it's necessary?

You have to load image every time you want to iterate them, to get "fresh" img elements

Try this

function example(){
    let n = document.getElementsByTagName("img");  // Moved here
    for(tip of n){
        if(tip.src == "https://abs-0.twimg.com/emoji/v2/svg/1f1ea-1f1f8.svg"){
            tip.src = "https://abs-0.twimg.com/emoji/v2/svg/1f3f3-fe0f-200d-1f308.svg";
        }
    }
}

setInterval(example, 100);

It is not always that the images are shown with img tag.

If you see some cases on twitter, img tag's sibling is an element with img src in its styles. That element is showing the image. Obviously, this is not the case with every single image on twitter.

But for such a case, you change it's background by

let n = document.getElementsByTagName("img");

for(tip of n){
    r.previousSibling.style.backgroundImage='YourImage.png'
}

Also, you have to use some kind of interval to get results that are loaded later. Or you could detect DOM changes using Mutation Observer and only fire your function on DOM change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM