S Zombek
S Zombek

Reputation: 41

Generating a clickable HTML link from a javascript array

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:

Result

Upvotes: 4

Views: 883

Answers (2)

lissettdm
lissettdm

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

plc-dev
plc-dev

Reputation: 55

You could use the innerHTML property instead of innerText to append the link as an actual HTML-element.

Or alternatively follow the approach mentioned here and create a link element and append it to the "result"-node.

Upvotes: 2

Related Questions