Search code examples
htmljquerycssajaxhref

How to put an object's property to a href in AJAX?


I have a small question. How to put an object's property to href. I marked with comment the line

success: function (listOfTags) {
        let tagData = '';
        $.each(listOfTags, function (i, tag) {
            // ON THE NEXT LINE
            tagData += '<a href="http://localhost:5557/questions/tagged/" ???tag.id><li class="post-tag">' + tag.name + '</li></a>';
        });

        $('#recentTags').html(tagData);
    }

Solution

  • Try this:

    tagData += `<a href="http://localhost:5557/questions/tagged/${tag.id}"><li class="post-tag">${tag.name}</li></a>`;
    
    

    For a valid markup, the anchor should be inside the list item, and the latter should be the child of a ul like this:

    //before the loop
    tagData += '<ul>';
    
    tagData += `<li class="post-tag"><a href="http://localhost:5557/questions/tagged/${tag.id}">${tag.name}</a></li>`;
    
    //after the loop
    tagData += '</ul>';