Select class 的最后一个不为空的元素 (innerText !== "") with querySelector

Select the last element that is not empty (innerText !== "") of a class with querrySelector

我正在尝试 select class 的最后一个不为空的元素。

例如,这里我想select第二个元素:

<span class="test">A</span>
<span class="test">B</span>
<span class="test"></span>
<span class="test"></span>

但是因为innerText改变了(随着用户的动作),我不能只使用

document.querySelector(".test:nth-of-type(2)");

我已经试过了,但没用:

document.querySelector('.test:not(:empty):nth-last-of-type(1)');

function myFunction(){
  document.querySelector('.test:not(:empty):nth-last-of-type(1)').innerText = "test";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span class="test">A</span><br>
<span class="test">B</span><br>
<span class="test"></span><br>
<span class="test"></span><br>

<input type="button" value="change 2nd element" onclick="myFunction()"/>

为什么要为此使用querySelector?我建议这样做:

document
  .querySelectorAll('.test') // all with test class
  .filter(elem => elem.innerText !== '') // only not empty
  .at(-1) // last element

// or, if you need backward browser compatibility:
document
  .querySelectorAll('.test') // all with test class
  .filter(elem => elem.innerText !== '') // only not empty
  .reverse()[0]