【问题标题】:How to get a list of values from a specific CSS Selector如何从特定的 CSS 选择器中获取值列表
【发布时间】:2021-09-09 14:09:44
【问题描述】:

我想立即从特定 CSS 选择器中检索值列表。

我只想提取<strong> 中的文本。我正在使用:

document.querySelectorAll("p > strong")

但是我有一个节点列表...

NodeList(101) [strong, strong, strong, strong, strong, strong, strong, strong, strong,...]

我的目标是 innerText 像:

document.querySelectorAll("p > strong")[1].innerText

如何一次提取列表中的所有目标文本值?

【问题讨论】:

  • 标记为jquery 所以:$("p>strong").map((i,e) => $(e).text()).toArray()(不作为答案提供,因为它看起来不像你实际上想要jquery。

标签: javascript jquery css nodelist


【解决方案1】:

使用spread operator把它变成一个数组,然后使用map方法得到你需要的。

var array = [...document.querySelectorAll("p > strong")].map(a=>a.innerText);

console.log(array);
<p><strong>I</strong></p>
<p><strong>heart</strong></p>
<p><strong>To</strong></p>
<p><strong>Fart</strong></p>

【讨论】:

    【解决方案2】:

    如果你遍历你拥有的 nodeList,你的代码就可以工作

    虽然我使用 textContent - 相同但更标准

    const strong = document.querySelectorAll("p > strong")
    const texts = []
    for (let i = 0; i< strong.length;i++) texts.push(strong[i].textContent)
    console.log(texts)
    &lt;p&gt;Here is some &lt;strong&gt;text&lt;/strong&gt; and some &lt;strong&gt;more text&lt;/strong&gt;&lt;/p&gt;

    使用spread syntax在转换为数组后映射节点列表,但速度较慢(如果重要)

    const texts = [...document.querySelectorAll("p > strong")]
      .map(({textContent}) => textContent)
    console.log(texts)
    &lt;p&gt;Here is some &lt;strong&gt;text&lt;/strong&gt; and some &lt;strong&gt;more text&lt;/strong&gt;&lt;/p&gt;

    如果你需要jQuery

    const texts = $("p strong").map((_,e) => e.textContent).get();
    console.log(texts)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <p>Here is some <strong>text</strong> and some <strong>more text</strong></p>

    【讨论】:

    • textContentinnerText 不一样,也不比另一个更标准innerText 仅显示渲染文本,而 textContent 将显示目标元素中 &lt;style&gt;&lt;script&gt; 的 CSS 或 Javascript 代码。在这种情况下可能是相同的,但做出这样的假设可能不是一个好主意。
    • 早期标准化并不意味着它“更标准”。
    猜你喜欢
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2022-11-24
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    相关资源
    最近更新 更多