javascripttemplate-literals

Insert a variable into a template literal href tag


I am trying reference set up an href tag in a template literal using a dynamically generated variable pulled from an AJAX request but can't seem to figure it out. Nothing happens when I click the tagged element and for some reason the <a href/> doesn't show up when I inspect the element on the webpage.

Here is my code:

[...]  

data.forEach(([cafeId, cafeName, cafeAddress]) => {
            var myCol = $('<div id="col"></div>');
            var myPanel = $(
              `
              <div class="card-group">
              <div class="card card-block m-3 overflow-auto" style="width: 18rem;">
                <div class="card-body">
                  <h5 class="card-title venue-name" id=\"` + cafeName + `\"><a href="venue/\"` + cafeId + `\"></a></h5>
                  <h6 class="card-subtitle mb-2 text-muted venue-address"></h6>
                  <div class="dropdown">
                    <div class="venue-options" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></div>
                    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"><a id="share" class="dropdown-item" href="#">Share</a><a id="addToListNoModal" class="dropdown-item" href="#">Add to List</a></div>
                  </div>
                </div>
              </div>
            </div>
            `
            );
[...]

Here is a JSFiddle: https://jsfiddle.net/50pwyfde/12/


Solution

  • You have the wrong number of quotes in the <a> element. You're creating something that looks like

    <a href="venue/"cafeId">
    

    The extra quote is causing everything after it to parse incorrectly.

    Change that whole line to:

    <h5 class="card-title venue-name" id="${cafeName}"><a href="venue/${cafeId}"></a></h5>