【问题标题】:How to select a div element that does not have a class?如何选择没有类的 div 元素?
【发布时间】:2021-08-12 19:02:51
【问题描述】:
Sample HTML Element
<div data-testid="Custom Data Test"> 
  • 上面的div里面没有class。
  • 如何访问“data-testid”(我应该使用哪个选择器)

【问题讨论】:

  • 如果你使用jQuery,你可以使用像$(this).attr( "data-testid" )这样的this关键字来获取点击的div data-test属性值。

标签: html dom tags queryselector


【解决方案1】:

您可以使用querySelector()querySelectorAll() 并像这样按属性选择:

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>

【讨论】:

  • data-testid的值可以不断变化的动态环境中,有没有办法找到data-testid的值
  • 谢谢!!真的很感激
猜你喜欢
  • 2022-12-05
  • 2015-03-13
  • 2011-10-27
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 2021-01-18
相关资源
最近更新 更多