Sergi Sergi - 1 year ago 68
jQuery Question

Correct syntax to create an <a> tag with JQuery

I'm working with the Wikipedia API and I'm trying to display the result of JSON data. My first two elements work and they display the data correctly:

var link = $("<a href=</a>")
var newEl = $("<li></li>");
var newParagraph1 = $("<p></p>");
var newParagraph2 = $("<p></p>");
var list = $("#list");


For the third element I want a simple clickable link to the Wikipedia page that is giving me that information, something like:

newEl.append(newParagraph2.append("<a href =" + data[3][0] + ">" + " </a>"));

But it's not working. If I change "newParagraph2.append" for "newParagraph2.text", then I do get the text but everything is turned into a string I assume, not an actual tag. What is the correct way to create an tag, insert the "data[3][0]" after the href= and close the tag?

Answer Source

Looks like you're just missing the internal quotes and some text:

newEl.append(newParagraph2.append('<a href ="' + data[3][0] + '">' + 'Some Clickable Text</a>'));

Also, get rid of the link variable if you're not using it. If you are using it, change it to

var link = $("<a></a>")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download