How do I add an image in my Table in jQuery's

Viewed 32

So I am trying to instead of have the svg links of images to have the image actually show in the table. Can someone help me?

var url3 = "https://restcountries.eu/rest/v2/region/europe";
$.getJSON(url3, function (landen2, status) {
    //console.log("Data:", data);
    //console.log("Status:", status);
    laadTable(landen2);
});

function laadTable(landen2) {
    var landtable2 = $("<table>").addClass("tbl_sm");
    var tl2 = $("<tr>")
        .append($("<th>").html("name"))
        .append($("<th>").html("vlag"))
        .append($("<th>").html("neighboring countries"))
    landtable2.append(tl2);

    $(landen2).each(function (key, landen2) {
        var x = landen2.perc * 100;
        tl2 = $("<tr>")
            .append($("<td>").html(landen2.name))
            .append($("<td>").html(landen2.flag))
            .append($("<td>").html(landen2.borders))
        landtable2.append(tl2);
    });

    $("#divEind").append(landtable2);
}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- jQuery CDN -->
    <div id="contentJA">
        <div id="divEind"></div>
    </div>

1 Answers

To achieve this simply build an img element and set the landen2.flag value as its src.

Also note that you can improve the performance of the JS by reducing the number of times you update the DOM. You can achieve this by creating HTML as strings and appending them once, and also using map() to build an array of the new <tr> to add in one operation instead of in each iteration of the loop.

var url3 = "https://restcountries.eu/rest/v2/region/europe";
$.getJSON(url3, function(landen2, status) {
  laadTable(landen2);
});

function laadTable(landen2) {
  let $table = $("<table>").addClass("tbl_sm");
  let $header = $("<tr><th>name</th><th>vlag</th><th>neighboring countries</th></tr>").appendTo($table);
  let rows = landen2.map(o => {
    let $row = $(`<tr><td>${o.name}</td><td><img src="${o.flag}" /></td><td><ul></ul></td></tr>`);
    let borders = o.borders.map(b => `<li>${b}</li>`);
    $row.find('ul').append(borders);
    return $row;   
  });
  $table.append(rows).appendTo('#divEind');
}
img {
  width: 75px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- jQuery CDN -->
<div id="contentJA">
  <div id="divEind">
    Loading...
  </div>
</div>

Related