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

175
Views
Javascript grabbing button inside div with id

it seems like, when a div tag is added between the following code:

 <div id="fixed-drop">
  <button type="button" class="dropdown-btn">Show;</button>
  </div>

The following Javascript code is not able to get the item, failing with

Uncaught TypeError: Cannot read properties of undefined (reading 'getElementsByClassName')

But if that div tag is deleted, javascript is able to grab the button: I have tried the following js codes:

  var dropdown = document.getElementById("fixed-drop").document.getElementsByClassName("dropdown-btn");

  var dropdown = document.getElementById("fixed-drop")[0].document.getElementsByClassName("dropdown-btn");

Without div this works:

  var dropdown = document.getElementsByClassName("dropdown-btn");

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Document.querySelector() can be used to select the child element:

var dropdown = document.getElementById("fixed-drop").querySelector('.dropdown-btn');

dropdown.addEventListener('click', function() {
  console.log('Clicked');
});
<div id="fixed-drop">
  <button type="button" class="dropdown-btn">Show</button>
</div>

about 4 years ago · Juan Pablo Isaza Report

0

The problem occurs that you first fetch the div with document.getElementById("fixed-drop"). If yor are remove it, the funtion will return null. and the next function cant access null.

Solution Use querySelector instead of chaining getElementById() functions.

const btn1 = document.querySelector('.dropdown-btn')
console.log('without select parent div:',btn1)

const btn2 = document.querySelector('#fixed-drop .dropdown-btn')
console.log('with select parent div:',btn2)
 <div id="fixed-drop">
  <button type="button" class="dropdown-btn">Show;</button>    
  </div>

about 4 years ago · Juan Pablo Isaza Report

0

 var dropdown = document.getElementById("fixed-drop").document.getElementsByClassName("dropdown-btn");

""" document.getElementById("fixed-drop") """ this is an element. You can't element.getElementsByClassName("dropdown-btn") on element.

You can use querySelector.

var dropdown = querySelector('#fixed-drop .dropdown-btn');
about 4 years ago · Juan Pablo Isaza Report
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!