Zeke Young Zeke Young - 1 year ago 68
HTML Question

Is there a substitution for multiple IDs?

So I tried using the same Id on multiple elements, and... It didn't work. I looked it up and it said that it wouldn't work. So it said that classes would be better. It didn't help though. This is my script:

<a class="links" style="position:absolute;top:30">Link 1</a>
<a class="links" style="position:absolute;top:10">Link 2</a>

links.href = "https://google.com";

But it still didn't work. Am I just doing it wrong? Do I do it another way?
Thanks for the help!

EDIT: For those of you who don't know, I'm trying to give the two links the same href. I'm not actually going to do that, but it's just an example of my problem.

Answer Source

If you are trying to give all of your anchors with class "links" the same href, then you need to use one of the DOM methods that finds elements by class and returns a list of them, and then you need to loop over the items in the list.

var anchors = document.getElementsByClassName("links");
for (var i = 0; i < anchors.length; i++) {
  anchors[i].href = "https://google.com";

Here I've used the .getElementsByClassName() method, but you could also use the document.querySelectorAll() method with a selector of ".links".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download