Search code examples
javascriptlisthref

Adding href to anchor using JavaScript


I created a menu bar and created dynamically the li and anchor using js. Now can I add the href and text usng JavaScript to each of the created list:
<li><a></li></a> <li><a></li></a>.. so when clicking on any of the list items, it moves to the linked section on the page.


Solution

  • Select and iterate over your li>as and set their href and any other attribute you want. Something like below

    const links = [{
      title: 'Google',
      link: 'google.com'
    }, {
      title: 'Yahoo',
      link: 'yahoo.com'
    }, ];
    
    document.querySelectorAll('li>a').forEach((itm, index) => {
      if (index >= links.length) return;
      itm.href = links[index].link;
      itm.text = links[index].title
    })
    <ul>
      <li>
        <a />
      </li>
      <li>
        <a />
      </li>
    </ul>

    Or you can add lis dynamically according to your array of links.

    const links = [{
      title: 'Google',
      link: 'google.com'
    }, {
      title: 'Yahoo',
      link: 'yahoo.com'
    }, ];
    
    let ul = document.getElementById('nav');
    
    links.forEach(itm => {
      let li = document.createElement("li");
      let link = document.createElement("a");
      link.href = itm.link;
      link.text = itm.title
      li.appendChild(link)
      ul.appendChild(li)
    })
    <ul id="nav"></ul>