如何 select 没有 class 的 div 元素?
How to select a div element that does not have a class?
Sample HTML Element
<div data-testid="Custom Data Test">
- 上面的div里面没有class
- 如何访问“data-testid”(我应该使用哪个选择器)
您可以像这样按属性使用 querySelector()
或 querySelectorAll()
和 select:
const div = document.querySelector('div[data-testid="Custom Data Test"]');
div.textContent = "blah";
const divs = document.querySelectorAll('div[data-testid]');
divs.forEach( (e,i) => e.textContent = e.textContent + " this is div number " + i + " and data-testid attribute is " + e.dataset.testid);
Sample HTML Element
<div data-testid="Custom Data Test"></div>
<div data-testid="Custom Data Test 2"></div>
<div data-testid="Custom Data Test 3"></div>
Sample HTML Element
<div data-testid="Custom Data Test">
- 上面的div里面没有class
- 如何访问“data-testid”(我应该使用哪个选择器)
您可以像这样按属性使用 querySelector()
或 querySelectorAll()
和 select:
const div = document.querySelector('div[data-testid="Custom Data Test"]');
div.textContent = "blah";
const divs = document.querySelectorAll('div[data-testid]');
divs.forEach( (e,i) => e.textContent = e.textContent + " this is div number " + i + " and data-testid attribute is " + e.dataset.testid);
Sample HTML Element
<div data-testid="Custom Data Test"></div>
<div data-testid="Custom Data Test 2"></div>
<div data-testid="Custom Data Test 3"></div>