Search code examples
jquerydynamichtml-tablehref

Create dynamic href inside table cell


My problem is this:

I am trying to create some cells in a table, which will be filled by data that I extract from an XML document, but I also want those cells to be hyperlinks. I am doing this:

var table = $('<table></table>').addClass('table');
for(i=0;i<x.length;i++){
    var row = $('<tr></tr>').text(x.item(i).getAttribute("id")).attr('href', 'www.my-url.com/'+x.item(i).getAttribute("id"));
    table.append(row);
}

The cells are filled correctly with the text that I want, but the cells are not clickable. I do not get any errors in the console. Any idea what I am doing wrong?


Solution

  • You can't set an href attribute on a <tr> tag and expect it to work like an <a> tag. Instead, you need to put an <a> tag inside the <tr> tag. You can do that like this:

    var table = $('<table class="mytable"></table>');
    for (var i = 0; i < x.length; i++) {
        var txt = x.item(i).id;
        var url = 'http://www.my-url.com/' + txt;
        var row = $('<tr></tr>').html('<a href="' + url + '">' + txt + '</a>');
        table.append(row);
    }
    

    That method creates the HTML and lets the browser parse it. You could also create the elements directly like this:

    var table = $('<table class="mytable"></table>');
    for (var i = 0; i < x.length; i++) {
        var txt = x.item(i).id;
        var url = 'http://www.my-url.com/' + txt;
        var row = $('<tr></tr>')
        var link = document.createElement("a");
        link.href = url;
        link.innerHTML = txt;
        row.append(link);
        table.append(row);
    }