【问题标题】:Problems with acessing buttons with JS and BootstrapProblems with acessing buttons with JS and Bootstrap
【发布时间】:2022-12-01 20:08:51
【问题描述】:
I have a Bootstrap 5 button, that I'm trying to acess trough JS so I can disable it trough the Attribute.
My test code looks like this:
Script in Header:
`
<script>
console.log(document.getElementsByName("test")[0]);
</script>
My Body with the button
<body>
<div name="test" class="btn bg-secondary">bestanden?</div>
</body>
`
If I run the command without an Index I get a list, in which the button is, if I try to get the first button, it will only show undefined
【问题讨论】:
标签:
javascript
html
bootstrap-5
【解决方案1】:
You should either use document.addEventListener("DOMContentLoaded", ()=>{}) or move you code to the end of the body. Your script is currently being executed before the bodies DOM content has loaded.
<html>
<head>
<script>
const button = document.getElementsByName('test');
console.log('button', button);
</script>
</head>
<body>
<button name="test">Test</button>
</body>
</html>
As you can see in the example above, the list is empty.
Now lets add a DOMContentLoaded listener
<html>
<head>
<script>
document.addEventListener("DOMContentLoaded", () => {
const button = document.getElementsByName('test');
console.log('button', button);
});
</script>
</head>
<body>
<button name="test">Test</button>
</body>
</html>
Now we get our button and can do whatever we want with it.