Javascript 如何查询SVG元素并获取其标题?
我有以下标记,其中顶级元素包含带有标题检查图标的标记:Javascript 如何查询SVG元素并获取其标题?,javascript,dom,svg,selectors-api,Javascript,Dom,Svg,Selectors Api,我有以下标记,其中顶级元素包含带有标题检查图标的标记: <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>
<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>
使用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);
使用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);