Updating the value of data attribute using jQuery

I have the following HTML code:

<a class="toggle" href="#toggle">
    <img src="app/css/images/tock.png" alt="No" data-id="4" data-block="1">
</a>

I want to update the value of the src and data-block attributes using jQuery. How do I do this?

Update: As I have many image elements, I want to update the value of a specific image by using data-id.


Solution 1:

$('.toggle img').data('block', 'something');
$('.toggle img').attr('src', 'something.jpg');

Use jQuery.data and jQuery.attr.

I'm showing them to you separately for the sake of understanding.

Solution 2:

$('.toggle img').each(function(index) { 
    if($(this).attr('data-id') == '4')
    {
        $(this).attr('data-block', 'something');
        $(this).attr('src', 'something.jpg');
    }
});

or

$('.toggle img[data-id="4"]').attr('data-block', 'something');
$('.toggle img[data-id="4"]').attr('src', 'something.jpg');

Solution 3:

I want to change the width and height of a div. data attributes did not change it. Instead I use:

var size = $("#theme_photo_size").val().split("x");
$("#imageupload_img").width(size[0]);
$("#imageupload_img").attr("data-width", size[0]);
$("#imageupload_img").height(size[1]);
$("#imageupload_img").attr("data-height", size[1]);

be careful:

$("#imageupload_img").data("height", size[1]); //did not work

did not set it

$("#imageupload_img").attr("data-height", size[1]); // yes it worked!

this has set it.

Solution 4:

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');