Brett Cole Brett Cole - 1 year ago 30
jQuery Question

how to use an es6 template inside of html a tag href

Hey everyone this is the first time asking a question on here. So here we go. I have a ajax request with json return. I'm trying to now take the response and dynamically create the recipe title but also create an a href with the response data.

$( window ).load( function() {
$.get({
url: window.location.href + ".json"
}).success( function( response ) {
console.log( response );
let $title = $( ".js-title" );
let reviewCount = 0;

while( reviewCount < $title.length ) {
let recipe_title = response[reviewCount].recipe.title;
let href = response[reviewCount].location.href;

$title[reviewCount].prepend( `<a>${ recipe_title }</a>` ).attr('href', `${ href }`);
reviewCount++;
}
});


});

I'm having trouble figuring out the href part of things.

A.J A.J
Answer Source

Can add href in the template( while creating element ) and no need to use attr function.

example snippet to support above statement:

function prepend() {
  let title = 'something';
  let href = 'something/else'
  $('div').append(`<a href='${href}'>${title}</a>`)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="prepend()">Click here</button>
<div></div>

To User stand what is wrong with what you did:

No doubt jQuery prepend method is chainable but it will return the element that it applied upon. Therefore if you open inspector you should see href is getting added in $title[reviewCount] element.

To do this correct you need to construct the a element and then prepend it.

Example snippet.

function prepend() {
  let title = 'something';
  let href = 'something/else';
  $('div').prepend($('<a></a>').text(`${title}`).attr('href', `${href}`))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="prepend()">Click here</button>
<div></div>

To prepend in specific element:

We need to use eq method of Jquery, again this is cahinable.

Use:

$title.eq(reviewCount).prepend($('<a>').text(`${ response[reviewCount].recipe.title }`).attr('href', http: //localhost:3000/recipes/`${recipe_id}`));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download