首页 > 解决方案 > 我可以按 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)
                })

标签: javascripthtmldom

解决方案


您可以使用一些 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>


推荐阅读