0

I have a list of 20+ links across a site. For example:

/one2one/r/Data/Quote/
/one2one/r/Data/Quote/business/
/one2one/r/Data/Quote/commercial/ 

They all commonly contain the same query strings.

The intention is to set attributes through Adobe DTM e.g. open in a new tab. This is currently what I have working for one of the links. However we have 20+ links across the site. Is there a way I can amend this so either it picks up all links that contain this query string or perhaps i can add them as an array and maintain manually? I've tested both but i'm not sure I am doing it correctly as neither work.

Any help would be appreciated. Thanks in advance.

var els = document.querySelectorALL("a[href='/one2one/r/Data/Quote/']");
for (var i=0; i < els.length; i++) {
  els[i].setAttribute("target", "_blank");
} 
CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
doyess123
  • 1
  • 1
  • 1
  • Firstly it's `querySelectorAll()` - note lowercase. Secondly, use a wildcard attribute selector. See the duplicate. – Rory McCrossan Jan 09 '20 at 11:02
  • In addition to what other responses said, I would note that the `*=` operator will match against the full `href` value, so you could potentially have false positives on links that have query params that contain the value, as well. If you want to be more strict, you can further filter them out inside your loop with e.g. `if (~els[i].pathname.indexOf('/one2one/r/Data/Quote/')){ /** matches path component, do something */ }` – CrayonViolent Jan 09 '20 at 15:20

1 Answers1

3

The All in querySelectorAll should not be all caps. And you just need to use a wildcard by adding an asterisk (*) in front of href in your selector like this:

var els = document.querySelectorAll("a[href*='/one2one/r/Data/Quote/']");
for (var i=0; i < els.length; i++) {
    els[i].setAttribute("target", "_blank");
}

Check and run the following Code Snippet for a practical example of the above approach:

var els = document.querySelectorAll("a[href*='/one2one/r/Data/Quote/']");
for (var i=0; i < els.length; i++) {
    els[i].setAttribute("target", "_blank");
    els[i].style.color = "red";
} 
<a href="/one2one/r/Data/Quote/AAAA">AAA</a>
<a href="/one2one/r/Data/Quote/BBBB">BBB</a>
<a href="/one2one/r/Data/Quote/CCCC">CCC</a>
<a href="/one2one/r/Data/Quote/DDDD">DDD</a>

You can check out the other StackOverflow thread that this question is marked a duplicate of for a better understanding of what exactly does the asterisk (universal selector) do.

AndrewL64
  • 15,794
  • 8
  • 47
  • 79