【问题标题】:querySelectorAll() targeting rel="me" attribute AND href attribute containing "12345" [duplicate]querySelectorAll() 定位 rel="me" 属性和包含“12345”的 href 属性 [重复]
【发布时间】:2021-02-28 23:18:51
【问题描述】:

我这里有一个非常特殊的情况,我在其他任何地方都找不到。

我需要指向一个包含rel="me" 属性的<link> 元素和一个包含12345 的href="https://www.example.com/profile/12345" 属性。

<link rel="me" href="https://www.example.com/profile/12345"/>

我尝试使用document.querySelectorAll(),但我不知道如何格式化它以使AND 运算符工作。

if (document.querySelectorAll('[rel="me"], a[href*=123456]')[0])

关于如何做到这一点的任何想法?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    在 CSS 选择器中,“AND”根本不使用组合器。

    如果您有类型(或通用)选择器,则必须先使用它。

    选择&lt;link&gt;元素的类型选择器是link而不是a。

    link[rel="me"][href*="12345"]
    

    如果您想要第一个匹配项,请使用 querySelector() 而不是 querySelectorAll()[0]

    const el = document.querySelector('link[rel="me"][href*="12345"]');
    console.log(el);
    &lt;link rel="me" href="https://www.example.com/profile/12345"/&gt;

    【讨论】:

    • 太棒了!感谢您的提醒:)您只忘记了12345之间的引号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多