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
1 Answer
Reset to default 6With 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);