javascripthtmlforeachqueryselectall

querySelectorAll not working for multiple same id


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>

Solution

  • 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>