Search code examples
javascripthtmljsonurianchor

anchor tag not redirecting to link in html


I am calling an api and want to populate the uri property of api result into the html. I am calling a function and inside it I am trying to do in this way, running the loop 3 times and want to display 3 links with uri property of every object. But this is not running as expected and directing to "datares.jsonData.data[i]" and throwing error. what am doing wrong here?

let text = document.getElementById("textBody2");
for(let i =0; i< 10; i++){
text.innerHTML = "<a href= 'datares.jsonData.data[i].uri'>Linkkkk</a>";
}

<p id="textBody2" style="text-align: center;"></p>

{
  "jsonData": {
    "data": [
      {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "uri": 'http://dummy.restapiexample.com/api/v1/employees'
},
     {
    "userId": 2,
    "id": 1,
    "title": "delectus aut autem",
    "uri": 'http://dummy.restapiexample.com/api/v1/employee1'
},
      {
    "userId": 3,
    "id": 1,
    "title": "delectus aut autem",
    "uri": 'http://dummy.restapiexample.com/api/v1/employee2'
}
    ],
    "metadata": {}
  },
  "meta": {}
}


Solution

  • Few things:

    • "<a href= 'datares.jsonData.data[i].uri'>Linkkkk</a>" is a syntax error. It should be "<a href= "+datares.jsonData.data[i].uri+">Linkkkk</a>".

    • You are overwritting the HTML every loop cycle. Instead, use +=

    datares = {
      "jsonData": {
        "data": [{
            "userId": 1,
            "id": 1,
            "title": "delectus aut autem",
            "uri": 'http://dummy.restapiexample.com/api/v1/employees'
          },
          {
            "userId": 2,
            "id": 1,
            "title": "delectus aut autem",
            "uri": 'http://dummy.restapiexample.com/api/v1/employee1'
          },
          {
            "userId": 3,
            "id": 1,
            "title": "delectus aut autem",
            "uri": 'http://dummy.restapiexample.com/api/v1/employee2'
          }
        ],
        "metadata": {}
      },
      "meta": {}
    }
    let text = document.getElementById("textBody2");
    for (let i = 0; i < 3; i++) {
      text.innerHTML += "<a href= "+datares.jsonData.data[i].uri+">Linkkkk</a>";
    }
    <p id="textBody2" style="text-align: center;"></p>