简体   繁体   中英

How to add class/id to image based on its title or alt

I have this old website that needs some fixes, but they need to be quick.

Now I have this image with

Iam going to change the source with the following code:

$("img").click(function(){
    // Change src attribute of image
    $(this).attr("src", "images/card-front.jpg");
});    

But I cant select the image, since it is dynamic content.

How do I add a class or ID to this image, based on its title or alt?

If it's created dynamically, listen on document .
Also .click() is deprecated. Use .on() :

 $(document).on("click", '[alt="Schwimmbäder"]', function(){ // Change src attribute of image $(this).attr("src", "https://via.placeholder.com/200x200"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Click the image:</p> <img src="unknown" title="Schwimmbäder" alt="Schwimmbäder">

Targetting title and setting a class to an image and then use that new class to handle click events: this is how you can do it...

 $('img[title="imgTitle"]').addClass("newClass"); $('.newClass').click(function(){ $(this).attr("src", "https://homepages.cae.wisc.edu/~ece533/images/peppers.png"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img width="250" title="imgTitle" src="https://homepages.cae.wisc.edu/~ece533/images/fruits.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