Nar*_*esh 2 javascript svg dom selectors-api
我有以下标记,其中顶级元素包含<svg>标题为“检查图标”的标记:
<div data-testid="monday" role="button">
<svg viewBox="0 0 24 24">
<title>Check Icon</title>
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path>
</svg>
<span>Monday</span>
</div>
Run Code Online (Sandbox Code Playgroud)
对于我的单元测试,我需要确保 svg 元素存在并且其标题是“Check Icon”。svg 元素不一定是第一个子元素。做到这一点最简单的方法是什么?我已经选择了 data-testid="monday" 的父元素:
const buttonElement = document.querySelector('[data-testid="monday"]'));
Run Code Online (Sandbox Code Playgroud)
小智 6
通过 querySelector,您还可以使用 CSS 选择器语法来请求包含的标签:
var buttonElement = document.querySelector('[data-testid="monday"]');
// select the title element in the svg element as direct child nodes,
// if you need to be so specific:
// var titleElement1 = document.querySelector('[data-testid="monday"] > svg > title');
// or just select any title in the test object:
var titleElement = document.querySelector('[data-testid="monday"] title');
// get the text of the title by:
alert (titleElement.textContent);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4946 次 |
| 最近记录: |