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

前端 未结 4 994
旧时难觅i
旧时难觅i 2021-01-02 09:51

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

...

...

I need to

相关标签:
4条回答
  • 2021-01-02 10:37

    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);
    }
    
    0 讨论(0)
  • 2021-01-02 10:38

    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"

    0 讨论(0)
  • 2021-01-02 10:40

    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>
    
    0 讨论(0)
  • 2021-01-02 10:54

    I normally use the below:

    $(content).attr("src")
    where 
    content = "img src='/somesource/image.jpg'>" //removed < before img for html rendering in this comment
    
    0 讨论(0)
提交回复
热议问题