-2

How to fix it? It is not effecting the HTML. I want to add href from the javascript for all a tags with the same id. Thanks!

<a id='mySrct' style='background-color:red;color:#fff;border-radius:25px;padding:3px 8px;float:right;'>Demo</a>
<a id='mySrct' style='background-color:red;color:#fff;border-radius:25px;padding:3px 8px;float:right;'>Demo</a>
<a id='mySrct' style='background-color:red;color:#fff;border-radius:25px;padding:3px 8px;float:right;'>Demo</a>


<script>                
var name = "google.com"; 
var elms = document.querySelectorAll("#mySrct");
elems.forEach((elem) =< {
elem.href = "www." + name;
});
</script>
  • 3
    [Duplicate](https://www.google.com/search?q=site%3Astackoverflow.com+js+queryselectorall+duplicate+ids) of [How to get the div that has a duplicated id using querySelector()?](https://stackoverflow.com/q/28274887/4642212). – Sebastian Simon Oct 26 '20 at 17:38
  • Each DOM element should have a unique ID. – Tom O. Oct 26 '20 at 17:48
  • **ID must be UNIQUE** https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page – Mister Jojo Oct 26 '20 at 17:48

3 Answers3

0

For your code, element name and arrow function are incorrect. Check the below code.

var elems = document.querySelectorAll("#mySrct");

<a id='mySrct' style='background-color:red;color:#fff;border-radius:25px;padding:3px 8px;float:right;'>Demo</a>
    <a id='mySrct' style='background-color:red;color:#fff;border-radius:25px;padding:3px 8px;float:right;'>Demo</a>
    <a id='mySrct' style='background-color:red;color:#fff;border-radius:25px;padding:3px 8px;float:right;'>Demo</a>


    <script>                
    var name = "google.com"; 
    var elems = document.querySelectorAll("#mySrct");
    elems.forEach((elem) => {
    elem.href = "www." + name;
    });
    </script>
Sarun UK
  • 6,210
  • 7
  • 23
  • 48
0

You can't have multiple elements with the same id. Try doing this:

var name = "https://www.google.com";
var elems = document.getElementsByClassName("mySrct");
var run = elems.href = name;
.mySrct {
  background-color: red;
  color: #fff;
  border-radius: 25px;
  padding: 3px 8px;
  float: right;
}
<a class='mySrct' href="">Demo</a>
<a class='mySrct' href="">Demo</a>
<a class='mySrct' href="">Demo</a>
0

As stated by several others, the purpose of an id is to be unique. However, you can misuse it this way.

const elems = document.querySelectorAll('[id="no-proper-id"]');
for(const elem of elems) {
  console.log(elem.innerHTML);
}
<div id="no-proper-id">A</div>
<div id="no-proper-id">B</div>
<div id="no-proper-id">C</div>
<div id="no-proper-id">D</div>
<div id="no-proper-id">E</div>
Erik
  • 307
  • 1
  • 9