Skip to content Skip to sidebar Skip to footer

Using Javascript/jQuery To Get Attribute Values From An HTML String

I have an HTML string that contains text and images, e.g.

...

...

I need to get the src attribute of the first image.

Solution 1:

This

$("<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"


Solution 2:

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>

Solution 3:

I normally use the below:

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

Solution 4:

I solved this same issue trying to pull out the src url from an iframe. Here is a plain 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);
}

Post a Comment for "Using Javascript/jQuery To Get Attribute Values From An HTML String"