简体   繁体   中英

Find src attribute value of <img> tag in a Javascript string

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?

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") : "";

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM