简体   繁体   中英

How can you use jQuery to change all the avatar images' src attribute on Twitter.com systematically?

TL;DR: For all "img.avatar" on Twitter.com, I want to replace "_normal.png" for ".png" in the src attribute. See the code and the error I get below.

Context: I'm in the process of learning JavaScript and jQuery. So, I like to write small scripts to automate things as practice.

Problem: So, I have a Retina MacBook Pro and the 48px avatars on twitter.com look horrible (I know, #firstworldproblem, but bear with me). I noticed that the difference between the URL of the small 48px avatars and the large version is that the former ends with "_normal.png", while the latter simply ends with ".png". Example:

48px thumbnail: 
https://blablabla.com/7f11851408ac5220e361a22f1583e0db_normal.png 

Large version: 
https://blablabla.com/7f11851408ac5220e361a22f1583e0db.png

This being said, I thought of applying my jQuery knowledge and systematically removing the "_normal" at the end of the src attribute of every avatar image, which can be identified with the "avatar" class. What's the point? Just so that it lo Here's what I tried:

jQuery("img.avatar").each( function(){
    $(this).attr("src", $(this).attr("src").replace("_normal.png", ".png"))
});

And here's the error I get in the Console:

TypeError: Cannot call method 'replace' of undefined

What am I doing wrong? Why is $(this).attr("src") undefined, from what I understand of the error?

PS I'm relatively new to Stack Exchange, so give me a heads-up if I'm transgressing any conventions.

There exist some img elements without an src attribute in them. This would be what's causing a problem. Try adding a condition before changing the attribute, like so:

jQuery("img.avatar").each( function(){
    if($(this).attr('src'))
        $(this).attr("src", $(this).attr("src").replace("_normal.png", ".png"))
});

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