-3

I want to change (or control...) my <a> href with JavaScript. Here is my HTML structure:

<a class="google" href="#">LINK ONE</a>
<a class="google" href="#">LINK TWO</a>

And here my JavaScript code:

document.querySelectorAll("a.google").href = "https://google.com"

If I use querySelector(".google") it change the link, but just one of theme. If I use querySelectorAll(".google") or ("a.google") it doesn't change anything.

Can anyone help me?

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
qwyzex
  • 25
  • 4
  • 1
    actually `document.querySelectorAl` returns an array of elements, you should use an iteration like `for` to access each element then change the `href` – Mohammad Esmaeilzadeh Dec 03 '21 at 07:27
  • Read the docs: [`querySelector`](//developer.mozilla.org/docs/Web/API/Document/querySelector), [`querySelectorAll`](//developer.mozilla.org/docs/Web/API/Document/querySelectorAll). Please try using the [debugging capabilities](//ali-dev.medium.com/how-to-easily-debug-in-javascript-5bac70f94f1a) of your browser. Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`) and look at what `document.querySelector("a.google")` and `document.querySelectorAll("a.google")` are. [β€œCan someone help me?” is not an actual question](//meta.stackoverflow.com/q/284236/4642212). – Sebastian Simon Dec 03 '21 at 07:37

1 Answers1

2

document.querySelectorAll returns an array of elements. For this to work, and it was a good idea to think about it, you can do like so :

const links = document.querySelectorAll("a.google");
links.forEach(link => link.href = "https://google.com");
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65