0

I'm using the following script to get the ancestor of an element

<form id="form1">
  <div id="div1">
    <label id="label1">some label</label>
  </div>
  <div>
    <button id="btn1">
      Submit
    </button>
  </div>
</form>

this script works fine, as in it returns the form element

const btn = document.querySelector('#btn1');
console.log(btn);
const form = btn.closest('form');
console.log('form', form); // this returns the <form> element

but when I added some script to append an element using innerHTML, the form variable contains null.

const iconLoading = '<i class="fa-solid fa-spinner fa-spin"></i>';
const btn = document.querySelector('#btn1');
console.log(btn);
const parent = btn.parentElement;
parent.innerHTML += iconLoading;
const form = btn.closest('form');
console.log('form', form); // this returns null

here's the jsfiddle. what am I doing wrong? any help is appreciated

const iconLoading = '<i class="fa-solid fa-spinner fa-spin"></i>';
const btn = document.querySelector('#btn1');
console.log(btn);
const parent = btn.parentElement;
parent.innerHTML += iconLoading;
const form = btn.closest('form');
console.log('form', form);
<form id="form1">
  <div id="asd1">
    <label id="label1">some label</label>
  </div>
  <div>
    <button id="btn1">
      Submit
    </button>
  </div>
</form>
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
dapidmini
  • 1,490
  • 2
  • 23
  • 46
  • You can use the built in code tool to make a running example within the question. – Jeff B May 23 '22 at 14:31
  • 1
    I think using `innerHTML` caused the `btn` variable to reference a button that's no-longer on the page? `document.contains(btn)` is also false. -- Consider not using `innerHTML` – evolutionxbox May 23 '22 at 14:33
  • 1
    You'll need to call `document.querySelector('#btn1')` again using `closest()`. – 0stone0 May 23 '22 at 14:35
  • 1
    Some advice, I would stay away from adding in HTML for a loading spinner, instead have that spinner always present, but hidden. Show and hide it as needed. – Jeff B May 23 '22 at 14:36
  • const form = document.querySelector('#btn1').closest('form'); how @0stone0 says you have to select the element again, for some reason your const btn is not longer in the page... – Jorge Mejia May 23 '22 at 14:38
  • 2
    You should use `parent.insertAdjacentHTML( 'beforeend', iconLoading);`, it's prefered over `+= innerHTML` and fixes your problem. – 0stone0 May 23 '22 at 14:39
  • Use [`insertAdjacentHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) instead – Bergi May 23 '22 at 14:41

0 Answers0