Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a custom attribute to an element in Jquery

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

like image 972
Sebastien Avatar asked Nov 29 '11 08:11

Sebastien


People also ask

How do I add a custom attribute to an element?

So how do we add custom attributes to HTML elements? We can create any custom attribute, by adding, data-, followed by the attribute name.

How we can add attribute in jQuery?

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 .

Can I add custom attributes to HTML elements?

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.

How set data attribute in 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.


1 Answers

you can use jQuery .data() functionality.

var theDiv = $('#' + divID).data('winWidth', value);

Get the data back using

theDiv.data('winWidth');
like image 122
JGilmartin Avatar answered Sep 19 '22 16:09

JGilmartin