Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
make createElement a link on the IMG attribute

i've created an element in javascript that shows an image:

 const image = document.createElement('img');
                        image.setAttribute('class', 'imgGame');
                        image.setAttribute('alt', game.name );
                        image.setAttribute('title', game.name );
                        image.src = game.background_image;
                        card.appendChild(image);

now i've tried to add

image.setAttribute('href', mylinkVariable);

or

image.href =

but i can't make the image a link (target blank and nofollow) to a website.

what i'm doing wrong?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

wrap the <img> with an <a> and then add the href to it.

or

img.onclick = () => window.location.replace('YOUR URL');
about 4 years ago · Juan Pablo Isaza Relatório

0

You can't add link to img just wrap with a(link) tag like this;

const card = document.getElementById('card');
const link = document.createElement('a');
const image = document.createElement('img');
image.setAttribute('class', 'imgGame');
image.setAttribute('alt', game.name);
image.setAttribute('title', game.name);
image.src = game.background_image;
link.appendChild(image);
link.setAttribute('href', mylinkVariable);
card.appendChild(link);
about 4 years ago · Juan Pablo Isaza Relatório

0

Attach a click event listener to the image which assigns the desired location to window.location when the image has been clicked:

const image = document.createElement('img');
image.setAttribute('class', 'imgGame');
image.src = 'https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1';
document.body.appendChild(image);

image.addEventListener('click', () => location = "https://stacksnippets.net")

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda