看起来,当在以下代码之间添加div标记时:
<div id="fixed-drop">
<button type="button" class="dropdown-btn">Show;</button>
</div>下面的Javascript代码无法获得该项,
Uncaught TypeError: Cannot read properties of undefined (reading 'getElementsByClassName')但是,如果删除了div标记,javascript就能够获取按钮:我尝试了以下js代码:
var dropdown = document.getElementById("fixed-drop").document.getElementsByClassName("dropdown-btn");
var dropdown = document.getElementById("fixed-drop")[0].document.getElementsByClassName("dropdown-btn");如果没有div,这是可行的:
var dropdown = document.getElementsByClassName("dropdown-btn");发布于 2022-01-29 22:01:58
Document.querySelector()可用于选择子元素:
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>
发布于 2022-01-29 22:08:01
首先使用document.getElementById("fixed-drop")获取div会出现问题。如果您正在删除它,该函数将返回空。下一个函数不能访问null。
解决方案使用querySelector而不是链接getElementById()函数。
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>
发布于 2022-01-29 21:59:44
尝试删除对文档的第二次访问。
var dropdown = document.getElementById("fixed-drop").getElementsByClassName("dropdown-btn");
var dropdown = document.getElementById("fixed-drop")[0].getElementsByClassName("dropdown-btn");
由于getElementById返回一个元素,因此无法访问该元素的文档属性。
https://stackoverflow.com/questions/70910043
复制相似问题