Reputation: 643
I want to attach data attribute to element. My code is
$('<a>', {
class: 'like-comment
comment-like-color
comment_main_id_' + response.id,
text: '',
href: 'javascript:;',
}).appendTo(commentBody)
.append($('<i>', {class: 'fa fa-thumbs-up'}));
My HTML data generated is like
<a class="like-comment comment-like-color
comment_main_id_{{$comment['id']}}" href="javascript:
data-like-comment-id=" {{$comment[ 'id']}} ";">
<i class="fa fa-thumbs-up" aria-hidden="true"></i>
</a>
There's a data (data-like-comment-id) attribute, which I want to create using jQuery. Could someone please help me with it.
Upvotes: 0
Views: 89
Reputation: 8178
The main difference between $.fn.attr
and $.fn.data
is:
$.fn.attr: stores information/data directly on the element attribute which get visible for inspection, and they are available through element's native API.
$.fn.data: stores info where it cannot be accessible outside JQuery and it's more closed
Data set with attr()
$(element).attr('data-name')
element.getAttribute('data-name')
toodata-name
it is also accessible from $(element).data(name)
and element.dataset['name']
and element.dataset.name
Data set with .data()
.data(name)
use below for .attr()
usage
$('elm').attr(attname,attvalue);
use data-
prefix before to avoid collision
$('elm').attr('data-'+attname,attvalue);
use below for .data()
$('elm').data(attname,attvalue);
Upvotes: 2
Reputation: 3726
You may just add it in your argument list on creation:
$('<a>', {
class: 'like-comment comment-like-color comment_main_id_',
text: '',
href: 'javascript:;',
'data-like-comment-id': 'whatever'
}).appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or add it after using .attr()
:
http://api.jquery.com/attr/
$('<a>', {
class: 'like-comment comment-like-color comment_main_id_',
text: '',
href: 'javascript:;',
})
.attr('data-like-comment-id', 'whatever2')
.appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or using the .data()
function:
https://api.jquery.com/data/
This one wont show in the DOM
$('<a>', {
class: 'like-comment comment-like-color comment_main_id_',
text: '',
href: 'javascript:;',
})
.data('like-comment-id', 'whatever3')
.appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2
Reputation: 2612
Give your anchor element an id when you create
$('<a id="foo"></a>'); // Simplified for brevity
Then you can select it late add a data attribute with the $.data()
function:
const mycomment = "some value";
$("#foo").data("like-comment", mycomment);
Upvotes: 2
Reputation: 32354
Use the attr
property
$('<a>',{"class":'test',attr:{'prop':'value'}})
Upvotes: 2