Home > front end >  Getting data-id attribute from dynamic render divs
Getting data-id attribute from dynamic render divs

Time:10-03

I want to get a data-id attribute by clicking on a chosen card that i'm creating dynamically. How should i construct my checkPair function to get that result because right now im getting an error " The name "getAttribute" could not be found."

 function elementFromHtml(html: any):any {
      const template = document.createElement("template");
      template.innerHTML = html.trim();
      return template.content.firstElementChild;
    }
    
const pokemonCard = ( url: string) => {
  const card = elementFromHtml(`
        <div  data-id=${url} onclick="checkPair()">
        <img src=${url} alt='pokemon-image' />
        </div>
    `);
  container.appendChild(card);
};

const checkPair = () => {
  let cardId = getAttribute('data-id')
  console.log(cardId)
}

CodePudding user response:

getAttribute is a function property of Element.

By the way, you shouldn't use onclick, use event listeners instead:

function elementFromHtml(html: any):any {
      const template = document.createElement("template");
      template.innerHTML = html.trim();
      return template.content.firstElementChild;
    }
    
const pokemonCard = ( url: string) => {
  const card = elementFromHtml(`
        <div  data-id=${url}>
        <img src=${url} alt='pokemon-image' />
        </div>
    `);
  container.appendChild(card);
  card.addEventListener("click", e => checkPair(e.target));
};

const checkPair = (e: Element) => {
  let cardId = e.getAttribute('data-id')
  console.log(cardId)
}

CodePudding user response:

This can be done this way too.

function elementFromHtml(html) {
  const template = document.createElement("template");
  template.innerHTML = html;
  return template.content.firstElementChild;
}

const pokemonCard = (url) => {
  if (!url) return;
  const card = elementFromHtml(`
    <div  data-id=${url}>
      <img src=${url} alt='pokemon-image' data-id=${url}/>
    </div>
`);
  document.body.appendChild(card);
  card.addEventListener("click", function (event) {
    const { id } = event.target.dataset;
    alert(id);
  });
};

pokemonCard(
  "https://images.gameinfo.io/pokemon/256/p25f310g2.png"
);

  • Related