Reputation: 163
I create elements dynamically using jquery. this is my code
function showArticles(res) {
var output = '';
res.articles.forEach(function (item) {
output +=
'<div class="col-12 col-lg-4 item-article" data-name="'+ item.author +'>'+
'<p>' + item.description + '</p>'
+
'</div>'
});
articleWrapper.append(output);
I want to get access to the data-name
attribute
var itemArticle = $('.item-article').attr("data-type");
console.log(itemArticle)
Return undefined
.
How to get access to the data-name
attribute why is this happening?
Upvotes: 1
Views: 55
Reputation: 13222
The code you tried to use is jQuery code. You will need to import the jQuery lib if you want to use that. Because this question is not tagged with jQuery i assume you want to us e plain javascript.
You can do this with the function querySelectorAll()
to get the matched elements. Loop over those elements and run the getAttribute()
function to get the attribute value.
var items = document.querySelectorAll('.item-article');
items.forEach((item) => {
var dataName = item.getAttribute('data-name');
});
Upvotes: 1
Reputation: 7004
You get the wrong attribute.
After showArticles
is called, you can do this:
var itemArticle = $('.item-article').attr("data-name");
// Or
var itemArticle = $('.item-article').data("name");
Upvotes: 1
Reputation: 14423
You can use var itemArticle = $('.item-article').data("name");
Upvotes: 1