Reputation: 2388
TLDR: I have a string that's in HTML format and I want to extract some text from it.
example html string (the actual HTML string I'm parsing is the value of event.target)
<div class="dclass">
<div class="dclass1 container">
<p class="pclass11 my-classes-here">text</p>
<img class="img-generic-class another-img-class" alt="my-alt-text1" src="my-img-source-here1">
</div>
<div class="dclass2 container">
<p class="pclass21 my-classes-here">text</p>
<img class="img-generic-class another-img-class" alt="my-alt-text2" src="my-img-source-here2">
</div>
</div>
How to I retrieve the string "my-alt-text2"? I thought of:
Thanks
Upvotes: 1
Views: 1561
Reputation: 98
var html = '<div><img class="img-class2" src="#" alt="Your alt here!"></div>'; //Your html string
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = html;
console.log(tmpDiv.querySelector('.img-class2').getAttribute('alt'));
Upvotes: 1