1

I wish to create divs, contents of the div, put those each in an tag, and then assign links the to the with JavaScript.

I apologize in advance for the inception of my situation.

This is what the interior of the sidebar looks like right now:

<div id="sidebar">
  <a href="link.a"><div>item a</div></a>
  <a href="link.b"><div>item b</div></a>
  <a href="link.c"><div>item c</div></a>
</div>

I want to create the inside the "sidebar" div using two arrays:

var linkList = ["link.a", "link.b", "link.c"];
var titleList = ["item a", "item b", "item c"];

I want the final html code to look like this:

<div id="sidebar" onload="createLinks()">
</div>

Unfortunately, I don't know how to code the JavaScript to make this work. If someone could help me, that'd be great!

3
  • the onload will not work like this, since it's not available on a div element. Commented Apr 9, 2019 at 19:45
  • Okay, is there a different way to approach it? Commented Apr 9, 2019 at 19:48
  • You could either take the onload onto the body element, listen for the load event in your script or mark your script with defer. Commented Apr 9, 2019 at 19:53

1 Answer 1

2

You can loop through one array using forEach() and add html using insertAdjacentHTML.

Note: As some users mentioned in comments onload can't be used on the elements. You could either call the function inside window.onload or just put <script> in the end of <body>

var linkList = ["link.a", "link.b", "link.c"];
var titleList = ["item a", "item b", "item c"];

let sidebar = document.querySelector('#sidebar');

linkList.forEach((x,i) => {
  sidebar.insertAdjacentHTML("beforeend",`<a href="${x}"><div>${titleList[i]}</div></a>`)
})
<div id="sidebar">
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.