Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating the value of data attribute using jQuery

Tags:

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.

like image 625
Ibrahim Azhar Armar Avatar asked Oct 24 '11 10:10

Ibrahim Azhar Armar


People also ask

How pass data attribute value in jQuery?

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').

Which jQuery function is used the change the value of attribute?

The jQuery attr() method is used to get the value of an attribute. It can also be used to change the value.

How add data attribute in jQuery?

$('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 .

How do you check if data attribute exists in jQuery?

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 .


1 Answers

$('.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.

like image 126
MarioRicalde Avatar answered Oct 11 '22 12:10

MarioRicalde