Skip to content Skip to sidebar Skip to footer

Mass Assignment For Elements In A For Loop

I'm dealing with pulling in information from an API and want to take that data and inserting it into certain elements of different classes within a for-loop. Right now I'm doing th

Solution 1:

You could code:

$('tbody td span').text(function() {
    var i = this.parentNode.parentNode.rowIndex - 1;
    return tracks[i][this.className];
});

In the above snippet rowIndex of the tr elements is used for getting a specific array's element by index. Using bracket notation ([index]) and the className of the span element the corresponding property's value is set by the text method. Here is a demo.

As the table has one 1 row in the thead element the rowIndex of the first tr child of the tbody element is 1. That's why the returned value is subtracted by 1.

As a note, you should consider generating the tr elements according to the returned data. Using a templating library can be an option.

edit: You could also use vanilla JavaScript:

var spans = document.querySelectorAll('tbody td span');
Array.prototype.forEach.call(spans, function (el) {
    var i = el.parentNode.parentNode.rowIndex - 1;
    el.textContent = tracks[i][el.className];
});

Solution 2:

You can rather use:

 $("span.number").eq(i).text(trackNumber);
 $("span.title").eq(i).text(trackTitle);
 $("span.duration").eq(i).text(trackDuration);

Solution 3:

How about:

var attr = $(this).attr("class");
$("." + attr).eq(i).text(tracks[i][attr]);

Post a Comment for "Mass Assignment For Elements In A For Loop"