Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!