I have some code where I\'ve added custom attributes which I want to change the value of.
Firstly, inventing your own attributes will mean your HTML is invalid and can lead to issues in your page. Secondly, val()
is used to directly change the value
property of the element, hence why it has no effect in your example.
To achieve what you require, use data-*
attributes, as they are intended for this purpose:
<div data-custom="someValue"></div>
$("#somebutton").click(function() {
// getter:
var foo = $('div').data('custom'); // = 'someValue'
// setter:
$('div').data('custom', 'someOtherValue');
});
Note that data()
maintains an object in memory so any amendments you make won't be visible in the DOM.
For more information: http://api.jquery.com/data
Your element isn't custom, it's still a div.
You can do a custom element like so.
<myCustomElement></myCustomElement>
Then select like
$('myCustomElement')...
An alternative is to use data-attributes.
<div data-myCustomData="test"></div>
Then select like so
var data = $('div').data('myCustomData')//data = 'test'