Home > other >  Adding href to anchor using JavaScript
Adding href to anchor using JavaScript

Time:09-25

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.

CodePudding user response:

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>

CodePudding user response:

First, you need to give every item a unique id. Then use their id as a reference and add their href attribute.

Let's consider your element is

<li><a id='list1'>Stackoverflow</a></li>

And the js code will be

<script>
      document.getElementById("list1").href = "https://stackoverflow.com"; 
</script>
  • Related