Skip to content Skip to sidebar Skip to footer

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, m

Solution 1:

you can use jQuery .data() functionality.

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

Get the data back using

theDiv.data('winWidth');

Solution 2:

I use the jQuery on-the-fly technique to accomplish that hack.

$(document).ready(function() {

  $('<div>').attr('id', 'attributename').attr('faron', 'Idunnoyoucanseeme').text('Hello, I am the element with made-up attribute built on the fly.  Made up attribute: faron').appendTo('#nest');

  var attributegrabber = $('#attributename').attr('faron');

  alert(attributegrabber);

});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="nest"></div>

Solution 3:

You can't. Use jQuery.data api instead to associate custom properties with element's jQuery wrapper. http://api.jquery.com/jQuery.data/

Solution 4:

You can add/set custom attribute in image also

var attr = 'data-img';
var message = 'Hello'
jQuery('img').attr(attr,message);

it will result

<img src="xyz.jpg"data-img="Hello">

Solution 5:

First check

$(this).css('background', 'url(' + randomItem.src + ')');

is working or not? If its working, put '' to your add attribute code like,

$(this).attr('element_id','4');

Post a Comment for "Add A Custom Attribute To An Element In Jquery"