Search code examples
javascriptgoogle-chromevariablesgoogle-chrome-extensiondomparser

Can't change value of a variable in JS, using parseFromString


I have this line at the very beginning of a Chrome extension:

var macroXML = parser.parseFromString(localStorage["myMacro"], "text/xml").getElementsByTagName("section");

After doing some changes, I try to update macroXML, but nothing happens.

alert(macroXML[1]);
macroXML[1] = 'RAWR';
alert(macroXML[1]);

No errors, no anything. It outputs the exact same thing.

Anyone perhaps know why?


Solution

  • You are dealing with a dynamic nodes list. It will change if the document changes, e.g. to remove the second element from the list you can do:

    macroXML[1].parentNode.removeChild(macroXML[1]);
    

    Or you replace it by a different node:

    var newNode = macroXML[1].ownerDocument.createElement("section");
    macroXML[1].parentNode.replaceChild(newNode, macroXML[1]);
    

    But you cannot work with that list as you would do with an array - for that you need an actual array. You can copy the list like this:

    var macroArray = Array.prototype.slice.apply(macroXML);
    macroArray[1] = 'RAWR';
    

    This will work as expected then.