Reputation: 1368
I am trying to write jason data into separate divs with class .name and data-key za data attr. I have problem with data and getting the right index for that.
Here is my buggy attempt. Console.log writes all keys, but the last function doesn't give divs the data attr
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link']['key']
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
container.appendChild(div);
});
$.each((".name"), function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
Upvotes: 0
Views: 92
Reputation: 3856
please try with this updated code
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link']['key']
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
container.appendChild(div);
});
$(".name").each(function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
Upvotes: 1
Reputation: 40639
You missed a $
in ('.names')
$.each
try this,
$.each($(".name"), function(index) {
// ----^ use $ here
$(this).data("key", keys[index]);
console.log(keys[index]);
});
or simply,
$(".name").each(function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
You can add key
while adding element
in container
like,
var i=0;
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
$(div).data("key", keys[i]);// set data here
container.appendChild(div);
i++;
});
Upvotes: 0