[SOLVED] Get attribute from HTML string (without jQuery)

Issue

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.

Solution

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'));

Answered By – Rohìt Jíndal

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *