简体   繁体   English

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

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

Sorry in advance - there are SO many variances of this question on SO, but none have resolved my issue.提前抱歉 - 这个问题在 SO 上有很多不同之处,但没有一个能解决我的问题。 I have read so many variations that I am now completely confused on how to do this.我已经阅读了如此多的变体,以至于我现在完全不知道如何做到这一点。

I have this Javascript function that appends UTM params to all offsite links except those with specific classes as such:我有这个 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';
    }   
})

Now, I need to prevent appending to现在,我需要防止附加到

ul.another_class li a

I have tried a myriad of syntaxes and formats, but just can't get it to work correctly.我尝试了无数的语法和格式,但就是无法正常工作。 Such as

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

and way too many more to list here.还有太多太多无法在此列出。 The selector ul.another_class li a , only the ul has a class - neither the li nor the a does.选择器ul.another_class li a ,只有ul有一个类—— lia都没有。

So, my question is both about the correct :not selector syntax AND the proper statement syntax.所以,我的问题是关于正确的:not选择器语法和正确的语句语法。 It is supposed to be应该是

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

or或者

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

or something else?或者是其他东西? I appreciate your expertise.我很欣赏你的专业知识。

It's not possible concisely with a single selector, because there is no parent selector .使用单个选择器是不可能的,因为没有父选择器 I think the best thing to do here would be to filter out the ul.another_class li a afterwards:我认为在这里做的最好的事情是过滤掉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