作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下标记,其中顶级元素包含 <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>
对于我的单元测试,我需要确保 svg 元素存在并且其标题是“Check Icon”。 svg 元素不一定是第一个子元素。做到这一点最简单的方法是什么?我已经选择了 data-testid="monday"的父元素:
const buttonElement = document.querySelector('[data-testid="monday"]'));
最佳答案
通过 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);
关于javascript - 如何查询 SVG 元素并获取其标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238910/
我是一名优秀的程序员,十分优秀!