Reputation: 95
I'm attempting to pull some URLs from an array and write them to the page as <a>
HTML elements.
As you can see in the jsfiddle below, for some reason the href is being set as [object text] and the URLs are being added as the link text, which means they don't work. How can I make it such that the href is the URL from my array and the link text is either the URL as well, or something like 'click here'?
Code
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);
Upvotes: 3
Views: 106
Reputation: 2521
The reason the url
is being set to [object Text] is that setAttribute
converts the value to a string. In your code url
is a textNode, which when converted to a string is serialized as, well, '[object Text]'
;
> String(document.createTextNode('testing'))
"[object Text]"
There really isn't any need to create a textNode for the url:
var urlX = document.createElement('a');
urlX.setAttribute('href', urls[i]);
urlX.appendChild(document.createTextNode('Click here'));
Upvotes: 0