cetaphil cetaphil - 1 month ago 27
Javascript Question

Create hyperlink with js dom

I'm trying to create a wikipedia viewer, get json data and then show it with a hyperlink that take you to the article. The problem is when I want to give the href attribute to a specific element.

$.getJSON(url1 + search + url2, function(data) {
for(i=0; i<data[1].length; i++) {
var p = document.createElement("P");
var id = p.setAttribute("id", i);
var t = document.createTextNode(data[1][i] + ': ');
var text = document.createTextNode(data[2][i]);
var a = document.getElementById(i);
var link = a.setAttribute("href", data[3][i]);
p.appendChild(t);
p.appendChild(text);
p.appendChild(link);
document.body.appendChild(p);
}
});


So, I'm calling the specific "p" element by Id(i value) and then I append to it the specific url. What am I missing?

Answer

It actually doesn't make much sense trying to correct parts of your code. The following is a cleaned up and corrected version of yours. Although it is untested, it should produce a format like <p>data[1][i]: <a href="data[3][i]">data[2][i]</a></p>.

$.getJSON(url1 + search + url2, function(data)
{
    for(var i = 0; i < data[1].length; ++i)
    {
        //main element
        var p = document.createElement("p");
        p.id = "element" + i;    //you should not use just numbers as IDs

        //preceding description
        var t = document.createTextNode(data[1][i] + ': ');

        //actual link
        var text = document.createTextNode(data[2][i]);
        var a = document.createElement("a");
        a.href = data[3][i];
        a.appendChild(text);

        //merge all of them together
        p.appendChild(t);
        p.appendChild(a);
        document.body.appendChild(p);
    }
});
Comments