3

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);

jsfiddle

4
  • That JSFiddle is empty.Please provide your code. Commented May 1, 2015 at 11:41
  • 2
    urlX.setAttribute('href', urls[i]); You missed that url is a TextNode object. Commented May 1, 2015 at 11:44
  • U need to get the content of text node by accessing the textContent property. e.g. urlX.setAttribute('href', url.textContent); Commented May 1, 2015 at 12:10
  • How do I change the link text to something else like 'click here'? Commented May 1, 2015 at 12:34

2 Answers 2

1

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

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

Comments

0

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'));

2 Comments

But then I get a link that looks like this: <a href="google.com">Click herehttp://www.google.com</a>
Hmm.. Could you provide a fiddle (jsfiddle.net)?

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.