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
.
jQuery attr() Method attr('name','value'); First of all, specify a selector to get the reference of an element and call attr() method with attribute name parameter. To set the value of an attribute, pass value parameter along with name parameter. In the above example, $('p').
The jQuery attr() method is used to get the value of an attribute. It can also be used to change the value.
$('div'). attr('data-info', 1); $('div')[0]. setAttribute('data-info',1); In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ( $('div[data-info="1"]') ), but when you use .
The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .
$('.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With