Formatting urls from an array as links

I am trying to pull some urls from an array and write them to a page as <a>

HTML elements.

As you can see in the jsfiddle below, for some reason the href is set to [object text] and the urls are added as link text, which means they don't work. How can I make it so that the href is the url from my array and the link text is either the url or something like "click here"?


    var title = document.createTextNode(titles[i]),
    author = document.createTextNode(authors[i]),
    url = document.createTextNode(urls[i]),
    titleX = document.createElement('h1'),
    authorX = document.createElement('h2'),
    urlX = document.createElement('a');
    urlX.setAttribute('href', url);




source to share

2 answers

Using urlX.setAttribute('href', url.textContent);



The reason the parameter is url

set to [object Text] is because it setAttribute

converts the value to a string. You url

have a textNode in your code which when converted to a string is serialized as, well, ' [object Text]'


> String(document.createTextNode('testing'))
"[object Text]"


There is really no need to create a textNode for the URL:

var urlX = document.createElement('a');
urlX.setAttribute('href', urls[i]);
urlX.appendChild(document.createTextNode('Click here'));




All Articles