How to change image and change class name using javascript ?
I try with my code but not work, What is wrong?
this code will
change class name from .black
to .red
change element from
<div id="abcd" style=" border-radius: 3px; border: 1px solid #ccc; padding: 10px;"> <img src="https://0.s3.envato.com/files/122605825/thumb.png"/> </div>
to
<div id="abcd" style=" border-radius: 3px; border: 1px solid #ccc; padding: 10px;">
<img src="https://0.s3.envato.com/files/118176445/thumbnail.png"/>
</div>
http://jsfiddle.net/28L8yk79/1/
javascript code
<script>
function test_fn() {
$('#12345-6).html('<div id="abcd" style=" border-radius: 3px; border: 1px solid #ccc; padding: 10px;"><img src="https://0.s3.envato.com/files/118176445/thumbnail.png"/></div>').addClass('red').removeClass('black');
}
</script>
Please solve me by using like my code. thank you
Try this:
<script>
function test_fn() {
$('#12345-6')
.removeClass('black')
.addClass('red')
.find('#abcd img')
.attr('src', 'https://0.s3.envato.com/files/118176445/thumbnail.png');
}
</script>
your missing an ' in the selector :
<script>
function test_fn() {
$('#12345-6').html('<div id="abcd" style=" border-radius: 3px; border: 1px solid #ccc; padding: 10px;"><img src="https://0.s3.envato.com/files/118176445/thumbnail.png"/></div>').addClass('red').removeClass('black');
}
</script>
see updated fiddle . missing an ' in the selector
function test_fn() {
$('#12345-6').html('<div id="abcd" style=" border-radius: 3px; border: 1px solid #ccc; padding: 10px;"><img src="https://0.s3.envato.com/files/118176445/thumbnail.png"/></div>').addClass('red').removeClass('black');
}
As @Beamer said, I would use something more practical. You don't need to inject html again, just modified your one.
function test_fn() {
var imageUrl = 'https://0.s3.envato.com/files/118176445/thumbnail.png'
$('#12345-6').addClass('red').removeClass('black').find('img:first').attr('src', imageUrl);
}
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.