Fred J. Fred J. - 3 months ago 10
jQuery Question

saving html element to a variable

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

Answer

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

myHTML = this.parentElement.cloneNode();