Farflame Farflame - 3 months ago 5x
HTML Question

Loop through array of elements, replace html with data

I have a table where each row contains several ratings, 5 of which need to be blanked when a certain action is taken and then the original rating put back in the when another action is taken. I've stored the original word in data, so my original line in HTML looks like this.

echo "<td data-Rating = $Rating class = 'outfieldlineuprating'>$Rating</td>";

In my JS, I find all the elements with 'outfieldlineuprating' like so..

SkillRatings = PlayerRow.find('.outfieldlineuprating');

It works up to this point (PlayerRow is fine). I know it works because when taking the first action (i.e blanking the elements), it works with ..


This puts ---- in all of the 5 elements with the 'outfieldlineuprating' class. Reversing it however, I'm struggling with. 'SkillRatings' at this point presumably contains some sort of array of the relevant td's, but I don't know how to loop through it, extract the data and insert that into the html. Here's what I'm trying but this doesn't work in JS.

for (var index = 0; index < SkillRatings.length; index++){
Rating = SkillRatings[index].attr('data-Rating');

This just gives the error : SkillRatings[index].attr is not a function


You are using jQuery and SkillRatings = PlayerRow.find('.outfieldlineuprating'); creates a jQuery object containing the elements.

SkillRatings[index] returns an actual element, not the jQuery object for that element

You would need to change SkillRatings[index].jQueryMethod() to

// or 

However this is easier done using SkillRatings.each which exposes this as the current element in the loop

Instead of using for loop try

     // "this" is current element
     $(this).html( $(this).data('Rating'));