0

This JS tries to save a html element to myHTML. but later when that element changes, the variable also changes.
How can I save a copy of myHTML to use it later?

let myHTML = '';
$('td.label').each(function() {
  if (this.textContent === "sign:") {
    if (!myHTML) myHTML = this.parentElement;
    return false;
  }
});

//later the elemnt gets changed
$('td.label').each(function() {
  if (this.textContent === "sign:") {
    this.parentElement.appendChild(some-html-element)
    return false;
  }
});

console.log(myHTML);  //it includes the some-html-element
Fred J.
  • 5,759
  • 10
  • 57
  • 106

2 Answers2

1

Use the cloneNode() method to set myHTML to a copy of the element:

myHTML = this.parentElement.cloneNode();

Ashwin Ramaswami
  • 873
  • 13
  • 22
  • it will not clone the rest of the tree which is not what I want. I want to clone the whole tree – Fred J. Aug 15 '16 at 11:45
0

I think because it is an object, js will reference it, and on change even your myHTML object changes too. This approach below should work correct, because it is not using DOM objects directly.

var myHTML;

$('td.label').each(function() {
    if( $(this).text() === "sign:" ) {
        if( !myHTML ) {
            myHTML = $(this).parent();
        }

        return false;
    }
});

$('td.label').each(function() {
    if( $(this).text() === "sign:" ) {
        $(this).parent().append("some-html-element");
        return false;
    }
});

console.log(myHTML);
eisbehr
  • 12,243
  • 7
  • 38
  • 63