javascript - 我可以按 id 或按类选择多个 html 元素吗?
问题描述
我在 html 文档中有 4 个按钮,我想根据函数的值更改所有按钮的文本内容。我一次只能为一个人做,但不能为所有人做。
我尝试使用 getElementById 来定位特定元素并用逗号分隔 id 但这不能解决问题。
//This is the only example that will actually change the text content for
only one of the 4 buttons
randomCapital.then(value => {
const btnSelect4Reneder = document.querySelector('#btn1')
btnSelect4Reneder.textContent = value
console.log(value)
})
//This will not fix the problem, none of the buttons will change their text
content
randomCapital.then(value => {
const btnSelect4Reneder =
document.getElementByClassName('btns')
btnSelect4Reneder.textContent = value
console.log(value)
})
//As expected, this way will not work either
randomCapital.then(value => {
const btnSelect4Reneder = document.querySelector('#btn1, #btn2, #btn3, #btn4')
btnSelect4Reneder.textContent = value
console.log(value)
})
解决方案
您可以使用一些 DOM API 函数来获取元素 - 我通常喜欢使用document.querySelectorAll
. 您必须将有效的 CSS 选择器传递给函数(如下所述)
选择器
一个 DOMString 包含一个或多个要匹配的选择器。此字符串必须是有效的 CSS 选择器字符串;如果不是,
SyntaxError
则抛出异常。有关使用选择器识别元素的更多信息,请参阅使用选择器定位 DOM 元素。可以通过使用逗号分隔多个选择器来指定多个选择器。
例如:
const nodeList = document.querySelectorAll('button');
const clickHandler = e => {
console.log(`You clicked ${e.target.textContent}`);
e.target.textContent = e.target.textContent + ' - Clicked!';
e.target.removeEventListener('click', clickHandler);
};
nodeList.forEach(node => {
node.addEventListener('click', clickHandler);
});
<button class="btn">Button 1</button>
<button class="btn">Button 2</button>
<button class="btn">Button 3</button>
<button class="btn">Button 4</button>
推荐阅读
- mysql - 左连接不返回所有结果
- node.js - Node & Heroku:启动脚本失败,但在我的本地机器上运行良好
- c# - 为什么我的 asp.net core cshtml 视图不呈现?
- python - 将额外参数传递给 networkx graphviz_layout 不起作用
- angular - Angular Crossfade 动画在最后一步跳跃
- bash - sed 用管道和星号替换字符串
- angular - 如何使用httpClient以角度下载大文件(> 1GB)?
- scheme - 过滤带有索引的列表 MIT-scheme
- javascript - 使用 Nuxt Js i18n 在头部添加 RTL 条件
- visual-c++ - Visual Studio MFC 在键入/动态时更改编辑控件中的文本