I have: document.querySelectorAll('div.stops') that appears with innerText "Direct" twice on the page.
So I want to apply a condition that if the text "Direct" appears twice, then do something. I have a code like below, but it does not give me the length of the number of times the word "Direct" appears. Instead, it just gives me the number of characters, which is 6.
for(let i=0; i < document.querySelectorAll('div.stops').length; i++){
if (document.querySelectorAll('div.stops')[i].innerText == 'Direct'){
// Do something
}}
Image where the text "Direct" appears 2 times
Screenshot of the console where I tried to find the length
Cache your elements. Use Array.from to create an array from the "array-like" list of nodes that querySelectorAll returns. That way you have access to array methods like filter.
filter out the elements that have 'Direct' as their textContent. Note: filter returns a new array.
If the length of that array is 2 do the thing.
const stops = document.querySelectorAll('.stops');
const direct = Array.from(stops).filter(stop => {
return stop.textContent === 'Direct';
});
if (direct.length === 2) {
console.log('Good');
}
<div class="stops">Direct</div>
<div class="stops">Karen</div>
<div class="stops">Indirect</div>
<div class="stops">Bus</div>
<div class="stops">Banana</div>
<div class="stops">Direct</div>