Update <li> href address via javascript

This works but I know there has to be a better, or correct way to write this without having to create id’s for the elements.

I am basically looking how to select the ul li elements and change the < a href> address.

<div id="footernav">
    <ul>    
        <li><a href="/MyShirtBuzz">Home</a> </li>        
        <li><a href="/MyShirtBuzz/Stores/Contact">Contact Us</a> </li>        
        <li><a href="/MyShirtBuzz/FAQHelp/Home">FAQ &amp; Help</a></li>
<li><a href="/MyShirtBuzz/Stores/Page/1000008/Sizing_Chart"><span style="list-style:none" class="linkbutton">Sizing Chart</span></a></li>
    
    </ul>
</div>

<script type="text/javascript">
  document.getElementById("footernav").firstElementChild.setAttribute("id", "newid");   

  document.getElementById("newid").firstElementChild.setAttribute("id", "footer-home-link");  

  document.getElementById("footer-home-link").firstElementChild.href="http://www.myshirtbuzz.com";
</script>

You might get all anchor elements inside #footernav like

var footer = document.getElementById('footernav')
var links = footer.querySelectorAll('a')

or just

var links = document.querySelectorAll('#footernav a')

Then you can access individual links just like array elements:

links[0].href = 'http://www.myshirtbuzz.com'
1 Like

How to you want to change the herf? Via event?

Thanks, Works perfectly. Much cleaner.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.