I had an interesting problem today at work – I needed to get the src attribute of an <img> tag that was not in the DOM.  I had a string containing HTML that was not actually part of the page, but I needed to parse it for information. I was not able to change the data, but I had access to an object with a property called “innerHTML” which contained the following string:

<img src="img/myimage.png" width="1700" height="500" />
<p>this is some text</p>

The easy (but ugly) way to solve this problem is to simply write the string into a hidden <div> on your HTML page, then extract what you need with jQuery. I really didn’t want to do this because I was going to be writing several large images into the page, and it just seems like a really lame way to handle the problem.

With a bit of help from this Stack Overflow thread, I found a better way to handle it. Simply cast your string into a jQuery object and you can use regular jQuery methods on it. here’s an example of how it works:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js">
</script>
<script type="text/javascript">
//create a sample object with a property containing HTML text:
var obj = {
    mystring: '<img src="img/myimage.png" width="1700" height="500"/>' +
        '<p>this is some text</p>'
}

$(document).ready(function() {
    //cast the string into jquery...
    //then use jquery's filter() function to isolate the image tag:
    var img_tag = $(obj.mystring).filter('img')[0];
    //to get the src attribute, we cast the above result into jquery again:
    var img_src = $(img_tag).attr('src');
    console.log(img_src); //ta da!!
});
</script>

This doesn’t come up very often, but it’s a good trick to have up your sleeve.