繁体   English   中英

document.querySelectorAll :not with multiple :not(s)

[英]document.querySelectorAll :not with multiple :not(s)

提前抱歉 - 这个问题在 SO 上有很多不同之处,但没有一个能解决我的问题。 我已经阅读了如此多的变体,以至于我现在完全不知道如何做到这一点。

我有这个 Javascript 函数,它将 UTM 参数附加到所有异地链接,但具有特定类的链接除外:

// Set the domain/URL of website.

var myDomain = "domain.com";

// Grab all links (anchor tags)
var links = document.querySelectorAll('a:not(.this-class)');

// Loop through all links
Array.prototype.forEach.call(links, function (link) {

// If a link goes offsite (not to my myDomain above)
if ( link.href.indexOf(myDomain) < 0 ) {

// Take the href and append the UTM parameters
link.href += '?utm_source=CampaignSource&utm_medium=CampaignMedium&utm_term=CampaignTerm&utm_content=CampaignContent&utm_campaign=CampaignName';
    }   
})

现在,我需要防止附加到

ul.another_class li a

我尝试了无数的语法和格式,但就是无法正常工作。

var links = document.querySelectorAll('a:not(.this-class),ul:not(.another_class li a)');

还有太多太多无法在此列出。 选择器ul.another_class li a ,只有ul有一个类—— lia都没有。

所以,我的问题是关于正确的:not选择器语法和正确的语句语法。 应该是

('a:not(.this-class), ul:not(.another_class li a)');

或者

('a:not(.this-class), ul.another_class:not(li a)');

或者是其他东西? 我很欣赏你的专业知识。

使用单个选择器是不可能的,因为没有父选择器 我认为在这里做的最好的事情是过滤掉ul.another_class li a之后:

for (const a of document.querySelectorAll('a:not(.this-class)')) {
  if (!a.matches('ul.another_class li a')) {
    // manipulate the href
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM