最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to query an SVG element and get its title? - Stack Overflow

programmeradmin3浏览0评论

I have the following markup where the top-level element contains an <svg> with the title "Check Icon":

<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>

For my unit test, I need to make sure that the svg element exists and its title is "Check Icon". The svg element is not necessarily the first child. What's the easiest way to do this? I have already selected the parent element with data-testid="monday":

const buttonElement = document.querySelector('[data-testid="monday"]'));

I have the following markup where the top-level element contains an <svg> with the title "Check Icon":

<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>

For my unit test, I need to make sure that the svg element exists and its title is "Check Icon". The svg element is not necessarily the first child. What's the easiest way to do this? I have already selected the parent element with data-testid="monday":

const buttonElement = document.querySelector('[data-testid="monday"]'));
Share Improve this question asked Oct 4, 2019 at 15:01 NareshNaresh 25.9k35 gold badges146 silver badges213 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

With querySelector you can ask for the contained tags as well using the CSS selector syntax:

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);
发布评论

评论列表(0)

  1. 暂无评论