Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda