1
  var titleLink=document.createElement("a");
  titleLink.setAttribute("href",'answers[3][i]');
  titleLink.innerHTML=answers[1][i];  

  newDiv.appendChild(titleLink);

When I click on the link when created through js, it shows page not found. But the same link when I add it explicitly using <a> tag in html opens correctly. What could be the problem??

Link to the entire code is here: http://codepen.io/jpninanjohn/pen/GZrzoG

3
  • titleLink.setAttribute("href",answers[3][i]);, remove the quotes of answers.. Commented Apr 7, 2016 at 14:52
  • That string is unlikely to be the href, try removing the quotes answers[3][i]. Also try using the console to debug: console.log(titleLink.href). Commented Apr 7, 2016 at 14:52
  • As said, you are setting the href attribute with a string instead of the array position codepen.io/anon/pen/yOpggx Commented Apr 7, 2016 at 14:53

3 Answers 3

1

I assume this is an exercise of FreeCodeCamp. As a FreeCodeCamper, it is nice to see another camper asking question in stackoverflow.

Anyway, you are almost near to the solution! Just make this tweak and you are good to go!

titleLink.setAttribute("target","_blank");
titleLink.setAttribute("href",answers[3][i]);
titleLink.innerHTML=answers[1][i]; 

It was a typo that you added single quotation over answers[3][i]. Optionally, I added an attribute to open the link in a new tab.

Hope it helps!

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

Comments

1

Remove the single quotes around answer:

  var titleLink=document.createElement("a");
  titleLink.setAttribute("href",answers[3][i]);
  titleLink.innerHTML=answers[1][i];  

  newDiv.appendChild(titleLink);

Comments

0

You have error in you code, you pass 'answers[3][i]' as a string. Try without brackets )

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.