KedeXx
KedeXx

Reputation: 3

javascript write object value to div

I need to write value of name from tracks object to plTitle using loop or some function if it exists . Please help I don't wan't to do this without JavaScript but I'm not very good at it so I need your help.

tracks = [{
  "track": 20,
  "name": "Magus - Smith St. Basement (01/08/04)",
  "length": "05:46",
  "file": "SSB01_08_04_M"
}, {
  "track": 21,
  "name": "Beneath The Painted Eye - Smith St. Basement (06/06/03)",
  "length": "13:08",
  "file": "SSB06_06_03_BTPE"
}];

$('.plItem .plTitle').each(function() {
  var trackName;

  for (var key in tracks) {
    trackName = ''
    var obj = tracks[key];
    naslov = obj.name;
    $(this).replaceWith('<div class="plTitle">' + trackName + '</div>');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="plwrap">
  <div class="plItem">
    <div class="plTitle"></div>
  </div>
  <div class="plItem">
    <div class="plTitle"></div>
  </div>
</div>

If you need additional info let me know!

Upvotes: 0

Views: 619

Answers (3)

Filip Hedman
Filip Hedman

Reputation: 417

You were close, but your variable names got messed up a bit. This is one possible solution for the loop part:

for (var key in tracks) {
    var obj = tracks[key];
    trackName = obj.name;
    $(this).replaceWith('<div class="plTitle">' + trackName + '</div>');
}

The difference is that the naslov variable changed name to trackName.

Upvotes: 0

Tobias Mesquita
Tobias Mesquita

Reputation: 269

tracks = [{
  "track": 20,
  "name": "Magus - Smith St. Basement (01/08/04)",
  "length": "05:46",
  "file": "SSB01_08_04_M"
}, {
  "track": 21,
  "name": "Beneath The Painted Eye - Smith St. Basement (06/06/03)",
  "length": "13:08",
  "file": "SSB06_06_03_BTPE"
}];

var plwrap = document.querySelector(".plwrap");
var tmplItem = document.getElementById("tmplItem").content;

while (plwrap.firstChild) {
  plwrap.removeChild(plwrap.firstChild);
}

tracks.forEach(function (track, indice) {
  var newItem = document.importNode(tmplItem, true);
  var plTitle = newItem.querySelector(".plTitle");
  plTitle.textContent = track.name;
  plwrap.appendChild(plTitle);
});
<template id="tmplItem">
  <div class="plItem">
    <div class="plTitle"></div>
  </div>
</template>
<div class="plwrap">

</div>

Upvotes: 1

empiric
empiric

Reputation: 7878

You probably don't need the .each-function here. You can use .text() with a function as it's parameter here:

$('.plItem .plTitle').text(function( index ) {
  return tracks[index].name;
});

This will write the title of the movei from your tracks array in the respective element dependet on the elements index.

Example

Upvotes: 2

Related Questions