0

I try to get an element by his href and add a class to this element in typescript, For this I tried :

let path = window.location.pathname;
let link = document.querySelectorAll("a[href="+path+"]");
console.log(link);

But my console.log throw me an error

querySelectorAll' on 'Document' is not a valid selector

Do you know how could I fix this ? Thanks

TheGame
  • 91
  • 1
  • 8
  • Also querySelectorAll returns a collection. You might want to consider just querySelector – mplungjan Sep 29 '20 at 12:39
  • 1
    Are you sure the href will be the path only? Perhaps you meant `document.querySelector(\`a[href*="${path}"]\`);` which see if the href contains the path instead of is equal to the path – mplungjan Sep 29 '20 at 12:44

1 Answers1

0

The question isn't TypeScript specific. It's just native Javascript :)

You're missing enclosing brackets around your path variable.

let path = window.location.pathname;
let link = document.querySelectorAll('a[href="'+path+'"]');
console.log(link);

Optionally, depending on what browsers you need to support - you can make this code more readable by using interpolation and template literals:

let path = window.location.pathname;
let link = document.querySelectorAll(`a[href="${path}"]`);
console.log(link);
Alex Mulchinock
  • 2,119
  • 1
  • 18
  • 25
  • You're suggesting I copied and pasted this answer from somewhere because I was too quick? Dude - I'm a full-time web developer. This really wasn't a difficult problem to figure out. – Alex Mulchinock Sep 29 '20 at 12:39
  • 1
    Ahh - my apologies. Misinterpreted the context of your comment :) Thanks for updating the second example. You spotted it before I could edit it! – Alex Mulchinock Sep 29 '20 at 12:42