代码之家  ›  专栏  ›  技术社区  ›  wyc

如何根据URL中的某些文本选择锚元素?

  •  1
  • wyc  · 技术社区  · 7 年前

    我试过这个:

    var els = document.querySelectorAll('a[href*="dabbing-through-the-snow"]')
    

    https://www.teepublic.com/t-shirt/3298777-funny-maltese-dabbing-through-the-snow-dab-christm?store_id=138163

    但是,我认为我的代码选择了页面上的所有链接。

    如何只选择包含文本的链接,例如, dabbing-through-the-snow ?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Unmitigated    7 年前

    你可以用 document.querySelectorAll([attribute*=value]) 选择属性包含值字符串的所有元素,因此代码应该是正确的。

    var els = document.querySelectorAll('a[href*="dabbing-through-the-snow"]');
    var anchors = document.querySelectorAll('a');
    console.log("Anchors:", anchors.length, "Matched Anchors:", els.length);
    <a href="">1</a>
    <a href="https://www.teepublic.com/t-shirt/3298777-funny-maltese-dabbing-through-the-snow-dab-christm?store_id=138163">2</a>

    您可能还希望使用 for 循环,如果你有更复杂的标准。

    var anchors = document.querySelectorAll("a");
    var href = "dabbing-through-the-snow";
    var found = [];
    
    for (var i = 0; i < anchors.length; i++) {
      if (anchors[i].href.includes(href)) {
        found.push(anchors[i]);
      }
    }
    console.log("Anchors:", anchors.length, "Matched Anchors:", found.length);
    <a href=“”>1</a>
        2
  •  1
  •   PHP Geek    7 年前

    您可以尝试使用以下代码获取带有字符串的href:

    const $aHref = $("a").filter((index, value) => $(value).attr('href').match(/\/dabbing-through-the-snow\//));
    const urlString = $.map($aHref, data => $(data).attr('href'));
    console.log(urlString);