I'm trying to add a custom attribute on my element using jquery :
$('.map-areas-div').rand(numElements).each(function(){
$(this).attr('element_id',4);
});
But in the end, my elements doesn't have a "element_id" attribute.
PS, my html elements look like :
<div type="ground" class="map-areas-div" style="position: absolute; top: 900px; left: 720px; height: 40px; width: 90px;"></div>
Thank you for help
So how do we add custom attributes to HTML elements? We can create any custom attribute, by adding, data-, followed by the attribute name.
You can add attributes using attr like so: $('#someid'). attr('name', 'value'); However, for DOM properties like checked , disabled and readonly , the proper way to do this (as of JQuery 1.6) is to use prop .
If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.
To set an attribute and value by using a function using this below syntax. $(selector). attr(attribute,function(index,currentvalue)) ; To set multiple attributes and values using this below syntax.
you can use jQuery .data() functionality.
var theDiv = $('#' + divID).data('winWidth', value);
Get the data back using
theDiv.data('winWidth');
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