Reputation: 61
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?
Upvotes: 1
Views: 515
Reputation: 479
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" />
Upvotes: 1
Reputation: 7303
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">
Upvotes: 4