4

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

2 Answers 2

2

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.

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

Comments

0

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>

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.