Home > database >  Getting the id of the anchor tag which was clicked with vanilla javascript
Getting the id of the anchor tag which was clicked with vanilla javascript

Time:10-13

I have pretty much the exact same problem as this:

Getting the id of the anchor tag which was clicked

Except I am using vanilla JavaScript and if I understand correctly, all of the answers provided for this question are in JQuery, which I don't know anything about.

I am working with an api called spoonacular.

I search some ingredients and I'm returned an array of objects containing recipes.

0
: 
{id: 661447, title: 'Square Deviled Eggs', image: 'https://spoonacular.com/recipeImages/661447-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
1
: 
{id: 638035, title: 'Chicken Cordon Bleu', image: 'https://spoonacular.com/recipeImages/638035-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
2
: 
{id: 641896, title: 'Easy Chicken Cordon Bleu', image: 'https://spoonacular.com/recipeImages/641896-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
3
: 
{id: 652359, title: 'Monte Carlo Sandwich', image: 'https://spoonacular.com/recipeImages/652359-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}
4
: 
{id: 663641, title: 'Tomato tarte tatin', image: 'https://spoonacular.com/recipeImages/663641-312x231.jpg', imageType: 'jpg', usedIngredientCount: 2, …}

I take the results and input them into the innerHTML like so (where data is the array of objects):

let recipeTitles = function(){
                return data.map(el => `<a onClick="showRecipe()" href="#"  id="${el.id}"><h2 >${el.title}</h2></a>`).join('')
            }
            
document.querySelector('#recipeTitle').innerHTML = recipeTitles()

I then want to make it so that whenever one of the individual anchor texts is clicked the the id is extracted so that i can run formulas using it.

This is what I wrote so far:

function showRecipe() {
    alert(this.id)
}

So the recipeTitles function adds onClick="showRecipe()" to the anchor tag, but when I click it returns 'undefined'.

I tried changing it to onClick="showRecipe" but then nothing happens.

Thank you for any help.

CodePudding user response:

You can pass the value of id in showRecipe() function inside anchor tag like below:

let recipeTitles = function () {
  return data.map(el => `<a onClick="showRecipe(${el.id})" href="#"  id="${el.id}"><h2 >${el.title}</h2></a>`).join('')
}

And then in function just pass a parameter id like below:

function showRecipe(id) {
    alert(id)
}

Now this will grab the value which is passed in the showRecipe() function as actual argument

  • Related