Reputation: 133
What's the selector for finding an element by both class name and text? For example:
<div class="a1">some text</div>
<div class="a1">some other text</div>
<div class="a2">some text</div>
Suppose I only care about the div element with class "a1" and "some text".
Thanks in advance, Alvaro
Upvotes: 1
Views: 83
Reputation: 1
You can use document.querySelectorAll()
with parameter selector "[class='a1']"
, array literal and spread element to cast NodeList
to Array
, Array.prototype.find()
to check and match .textContent
property of element to variable or string literal.
[...document.querySelectorAll("[class=a1]")]
.find(({textContent}) => textContent === "some text")
.style.color = "green";
<div class="a1">some text</div>
<div class="a1">some other text</div>
<div class="a2">some text</div>
Upvotes: 0
Reputation: 55644
You could use the :contains() selector like this:
$('.a1:contains("some text")');
Upvotes: 5