Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
javascript closest element by selector return null

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>

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!