Reputation: 41
I found code online that can select and print a random name from an array, and I'm trying to modify it to print a link instead of a name. I want that link to be clickable, as it would be normally in HTML. I'm not sure how to modify the javascript to do that, however.
This was my method for doing it below. But the result is that it just prints the HTML code on the page, not an interactive link. What's the better way to do this?
let btnRandom = document.querySelector('button');
let result = document.querySelector('h1');
let links = ['https://www.nytimes.com/2019/09/19/climate/air-travel-emissions.html', 'Link2', 'Link3', 'Link4', 'Link5', 'Link6', 'Link7'];
function getRandomNumber(min, max) {
let step1 = max - min + 1;
let step2 = Math.random() *step1;
let result = Math.floor(step2) + min;
return result;
}
btnRandom.addEventListener('click', () => {
let index = getRandomNumber(0, links.length-1);
result.innerText = '<a href ="' + links[index] + '"</a>';
});
Result of my current code:
Upvotes: 4
Views: 883
Reputation: 13078
Create an <a>
element using Document.createElement(). Then append the element to the h1
node with Node.appendChild()
let btnRandom = document.querySelector('button');
let result = document.querySelector('h1');
const links = ['https://www.nytimes.com/2019/09/19/climate/air-travel-emissions.html', 'Link2', 'Link3', 'Link4', 'Link5', 'Link6', 'Link7'];
function getRandomNumber(min, max) {
let step1 = max - min + 1;
let step2 = Math.random() *step1;
let result = Math.floor(step2) + min;
return result;
};
btnRandom.addEventListener('click', () => {
let index = getRandomNumber(0, links.length-1);
const a = document.createElement("a");
a.textContent= links[index];
a.href= links[index];
result.appendChild(a);
});
<button>Ramdom Link</button>
<h1></h1>
Upvotes: 0