2

So I have a for loop that iterates over a list of iframes:

    var iFr;
    for (var i = 0; i < iFrames.length; i++) {
      iFr = iFrames[i];

      if (isFooBar()) {
        iFr.dataset['sourceBackup'] = iFr.src; //assign src value to data-source-backup
        iFr.removeAttribute('src'); // remove src attribute
      }
    }

The weird part is that it seems to remove the src value also from dataset['sourceBackup'] or data-source-backup which I don't understand why. As I'm doing it AFTER assigning it to dataset['sourceBackup'].

UPDATE:

I even tried using object.assign() :

 iFr.dataset['sourceBackup'] = Object.assign({}, {'src': iFr.src}).src;

Yet still the iFr.dataset['sourceBackup'] dataset gets erased for some iframes elements but not for others which is confusing.

Update 2

The problem was with outer code not with the code here. I was having multiple references to the same iframe in different contexts. So this was causing the weird behavior.

CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186

1 Answers1

1

This is happening because both iFr.dataset['sourceBackup'] and iFr.src are pointing to the same object. The assignment does NOT make a copy of the object. Therefore, when you remove the object, it is not available regardless of which reference you use.

To actually clone the object, see this answer: How do I correctly clone a JavaScript object?

Jonathan M
  • 17,145
  • 9
  • 58
  • 91