I have an array with values that I want to dynamically insert into a string that, in turn, is part of an innerHTML string. I have worked out how to parse the array items using forEach but I can't work out how to take the values forEach returns and insert them into the string.
The purpose of this is to replace the following, very inefficient, code (you can ignore the fact that the current code uses iframe, it isn't directly relevant to my question):
let container = document.querySelector('.container');
let btnLoad50 = document.getElementById('btn50');
let btnLoad51 = document.getElementById('btn51');
let btnLoad53 = document.getElementById('btn53');
btnLoad50.addEventListener('click', function( btnFunc ) {
container.innerHTML = '<iframe src="pages/_route50.php" title="Route 50" width="900px" height="900px">';
})
btnLoad51.addEventListener('click', function( btnFunc ) {
container.innerHTML = '<iframe src="pages/_route51.php" title="Route 51" width="900px" height="900px">';
})
btnLoad53.addEventListener('click', function( btnFunc ) {
container.innerHTML = '<iframe src="pages/_route53.php" title="Route 53" width="900px" height="900px">';
})
The underlying HTML that I am targeting is this:
<p>Some unrelated text.</p>
<div class="btn_div">
<button name="load" class="btn">Click This</button>
</div>
<div class="container">
<p>Something will be added here</p>
</div>
This is what I've come up with so far:
This part works from the perspective that it parses the array using the forEach method and logs out a correctly iterated list of items in the console:
const rList = [50, 51, 53];
const btn = document.querySelector('.btn');
const container = document.querySelector('.container');
const routes = rList.forEach(e => console.log(`This is btn${e}`));
The following section gives me a ul list when I click the button but the content of each item is This is route btnundefined instead of This is route btn50, This is route btn51, etc:
btn.addEventListener('click', function() {
container.innerHTML = `
<ul>
<li>This is route btn${routes}</li>
<li>This is route btn${routes}</li>
<li>This is route btn${routes}</li>
</ul>`;
});
How can I bring it all together here? My desired outcome is the following:
- Parse the array, return the items in the array as values;
- Pass the items to my
eventListenerfunction, creating aullist in thecontainerelement in my page with incrementedbtn + itemstrings.
I'm looking for a vanilla JavaScript solution here. While I appreciate help from JQuery pros, I'm not using JQuery for this.