Reputation: 2535
I have been trying to get the 'src' in img tags inside a javascript variable that contains a block of HTML code dynamically generated/assigned.
Eg:
var post_body = "<div>This is an image <img src='abcd.jpg' /> and this is a paragraph <p>hi there</p> Here we have another image <img src='pqrs.jpg' /></div>"
the content of the 'post' variable is not predefined and it is dynamic and the HTML code in it always changes. To get the src of the image in it, I did the following. But it does not always work for me.
var firstimg = $(post_body).find("img:first").attr("src");
I was trying to get the first image of a blog post from the blog post's content but this does not work for some posts having images. How can this be done using javascript or jQuery without failing?
Upvotes: 0
Views: 34205
Reputation: 13
Late but, if don't want the images to be loaded use the below.
var div = document.createElement('template');
div.innerHTML = post_body;
if you create div element the remote images are loaded the moment you insert innerHTML, template prevents the requests.
Upvotes: 0
Reputation:
Perhaps you can try adding id to img
tag and then access it.
var oImg = document.getElementById('myImg');
var attr = oImg.getAttribute('src');
This is a pure js solution.
Upvotes: 0
Reputation: 324640
Using plain JavaScript, dump the HTML into a temporary element and extract it:
var div = document.createElement('div');
div.innerHTML = post_body;
var firstImage = div.getElementsByTagName('img')[0]
var imgSrc = firstImage ? firstImage.src : "";
// or, if you want the unresolved src, as it appears in the original HTML:
var rawImgSrc = firstImage ? firstImage.getAttribute("src") : "";
Upvotes: 8
Reputation: 20209
Change $(post_body)
to $(post)
Try
var post = "<div>This is an image <img src='abcd.jpg' /> and this is a paragraph <p>hi there</p> Here we have another image <img src='pqrs.jpg' /></div>";
var firstimg = $(post).find('img:first').attr('src');
Upvotes: 2