There are two links that should lead to different sections of the link depending on the anchor. I get the necessary links in link1 and link2 . Question: how now to transfer them to the links themselves without correcting html ?

 var link1 = document.getElementsByClassName("link1").href = "link#one"; var link2 = document.getElementsByClassName("link2").href = "link#two"; console.log(link1, link2); 
 <a class="link1" href="link">ссылка1</a> <a class="link2" href="link">ссылка2</a> 

  • if you take them from links, how do you want to transfer them to links? they are already there - Grundy
  • getElementsByClassName("link1") way, your code does not work, since getElementsByClassName("link1") returns a collection - Grundy
  • @Grundy to add on the fly in the generated html - Vasya
  • one
    A collection is several elements, not one, and adding the href property to the collection does not mean replacing the property in a specific element - Grundy
  • one
    I did not understand the question. The problem with collections in this case is that you need to run through them and set properties for specific elements, and you can't do collection.prop=10 and the prop property is set for everyone. - Grundy

2 answers 2

Well, if you don’t rule at all html then:

 $('.link1').click(function(e){ e.preventDefault(); location.href = $(this).attr('href') + '#one'; }); $('.link2').click(function(e){ e.preventDefault(); location.href = $(this).attr('href') + '#two'; }); 
 <a class="link1" href="link">ссылка1</a> <a class="link2" href="link">ссылка2</a> 

    In the code above, the main mistake is to try to add a property of the collection, rather than a specific element.

    To fix, you can either use id instead of class, or run through the collection in a loop, or take the first item from the collection, or use querySelector

     var link1 = document.getElementById("link1").href = "link#one"; var link2 = document.querySelector(".link2").href = "link#two"; [].forEach.call(document.getElementsByClassName('link3'), function(el) { el.href = "link#three"; }) console.log(link1, link2); 
     <a id="link1" href="link">ссылка1</a> <a class="link2" href="link">ссылка2</a> <a class="link3" href="link">ссылка3</a>