Using javascript / jQuery to get attribute values ​​from an HTML string

I have an HTML string containing text and images like

<p>...</p> <img src="..." /> <p>...</p> 

I need to get the src attribute of the first image. An image may or may not appear after <p> , and there may be more than one image or no image at all.

At first I tried adding a line to the DOM and filtering. But, if I do this, the browser requests all external resources. In my situation, this adds a lot of extra overhead.

My initial approach:

 var holder = $('<div></div>'); holder.html(content); var src = holder.find('img:first').attr('src'); 

How can I get src of the first image without adding HTML? Do I need to use regex, or is there a better way?

The solution should be based on javascript / jQuery - I do not use any server languages.

My question is very similar to: http://forum.jquery.com/topic/parsing-html-without-retrieving-external-resources

thanks

+7
javascript jquery attributes
source share
4 answers

it

 $("<p><blargh src='whatever.jpg' /></p>").find("blargh:first").attr("src") 

returns whatever.jpg , so I think you could try

 $(content.replace(/<img/gi, "<blargh")).find("blargh:first").attr("src") 

Edit

/<img/gi instead of "<img"

+12
source share

This should work:

 <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> //Document Ready: Everything inside this function fires after the page is loaded $(document).ready(function () { //Your html string var t = "<p><img src='test.jpg'/></p>" alert($(t).find('img:first').attr('src')); }); </script> </head> <body> </body> </html> 
+5
source share

I usually use below:

 $(content).attr("src") where content = "img src='/somesource/image.jpg'>" //removed < before img for html rendering in this comment 
+1
source share

I solved the same problem by trying to pull url src from iframe. Here is a simple JavaScript function that will work for any string:

 function getSourceUrl(iframe) { var startFromSrc = iframe.slice(iframe.search('src')); return startFromSrc.slice(5, startFromSrc.search(' ') - 1); } 
0
source share

All Articles