【问题标题】:how to search for an element using the queryselector and contains如何使用查询选择器搜索元素并包含
【发布时间】:2020-08-19 13:47:24
【问题描述】:

不知何故我想直接搜索一些文本? 可以使用 querySelector 吗?

Dom:

<div class="div1">
    <span class="text">
        <span> text to search </span>
    </span>
</div>



我尝试了以下但没有成功。

JS 代码:document.querySelector('div[contains("text to")]') = 失败

我知道简单的方法,例如:document.querySelector('span.text &gt; span')
我的例子很简单,我知道。我正在寻找类似于 selenium 的解决方案 selenium driver.find_element_by_link_text

我想独立搜索一个元素而不依赖于类或 id,有什么想法吗?

【问题讨论】:

标签: javascript contains queryselector


【解决方案1】:

不能直接使用querySelector。您必须先获取所有跨度,然后遍历它们以查看哪个具有您想要的文本。例如:

var results = []; 
document.querySelector("span").forEach(elem => {
    if (elem.textContent.includes("text to")) {
        results.push(elem);
    }
});

【讨论】:

  • 感谢您的回答,所以我得到了类似的结果,但我在 hopinig 有一个简单的替代方案。 (=
猜你喜欢
  • 2014-09-22
  • 1970-01-01
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多