Home > database >  Javascript grabbing button inside div with id
Javascript grabbing button inside div with id

Time:01-30

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

 <div id="fixed-drop">
  <button type="button" >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");

CodePudding user response:

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" >Show</button>
</div>

CodePudding user response:

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" >Show;</button>    
  </div>

CodePudding user response:

Try to remove accessing second time to the document.

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

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

Since getElementById returns a element, you can not access document property on that.

CodePudding user response:

you need to use it this way

const dropdown = document.getElementById('fixed-drop').getElementsByClassName('dropdown-btn');

In addition you should read this: https://developer.mozilla.org/es/docs/Web/API/Document/getElementsByTagName

<3

CodePudding user response:

 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');
  •  Tags:  
  • Related