querySelectorAll not working for multiple same id

745 Views Asked by At

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

There are 3 best solutions below

0
Sarun UK On BEST ANSWER

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>

0
hacker19374 On

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
Erik On

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>