'add href to const value
This title might not be correct, I am new. Basically, I want to apply the href to the name value so that when the element is displayed a can click it like an <a> element. Please help out if you can
const people = [
{name: 'test1'},
{name: 'test2'}
];
const list = document.getElementById('list');
function setList(group) {
clearList();
for (const person of group) {
const item = document.createElement('a');
const text = document.createTextNode(person.name.href);
item.appendChild(text);
list.appendChild(item);
}
if (group.length === 0 ) {
setNoResults();
}
}
Solution 1:[1]
First of all, I'm not sure if this a valid question for this forum. I would suggest you take some Javascript course and spend some time working on it first. Anyway, what you want to do would be something like this if I understood you correctly:
const people = [
{name: 'test1', link: 'url1'},
{name: 'test2', link: 'url2'}
];
const list = document.getElementById('list');
function setList(group) {
clearList();
for (const person of group) {
const item = document.createElement('a');
const text = document.createTextNode(person.name);
item.appendChild(text);
item.setAttribute('href', person.link);
list.appendChild(item);
}
if (group.length === 0 ) {
setNoResults();
}
}
You need to use the method "setAttribute" to set the attribute "href" of the "a" (anchor) element so that it gets the main property of a link. And also you need to store it on the people array objects as a new property to be able to access it this way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vigil |
