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
Get attribute from HTML string (without jQuery)

I'm trying to extract an image attribute from a HTML that's pulled in as a String.

Attempting to use https://stackoverflow.com/a/40311944/2981404 returns:

TypeError: Cannot read properties of undefined (reading 'slice')

My code is as follows:

const html[0] = '<img src="/img/image-example.png" class="image" title="What Im looking for..." alt="This is an example image">'
const startFromTitle = html[0].slice(
  html[0].search('title')
)
const title = startFromTitle.slice(5, startFromTitle.search(' ') - 1)
console.log(title) // expected "What Im looking for..."

I'd love to use jQuery, but on this project, I can't.

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

0

You must declare html as const first and then assign the html string to html[0].

And then you can remove title=" from the string (withoutTitle) and then search for '"' to find the end of the attribute.

const html = [];

html[0] = '<img src="/img/image-example.png" class="image" title="What Im looking for..." alt="This is an example image">';

const startFromTitle = html[0].slice(
  html[0].search('title')
);

const withoutTitle = startFromTitle.slice(
  7
);

const title = withoutTitle.slice(0, withoutTitle.search('"'));

console.log(title);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can achieve this by creating a temporary div element in DOM :

const htmlStr = '<img src="/img/image-example.png" class="image" title="What Im looking for..." alt="This is an example image">';

var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = htmlStr;

console.log(tmpDiv.querySelector('.image').getAttribute('title'));

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