使用JQuery从html和字符串内容中获取图像标记

时间:2018-01-08 10:36:27

标签: javascript jquery html

使用JQuery从html和字符串内容中获取图像标记。我想要图片标签表单内容并用它的alt属性替换它。对于。例如:

鉴于我的html字符串内容。

Hello this is long content with multiple images
<img alt=":*" src="kissing_heart.png"> and smiley is <img alt=":D" src="smiley.png">.

那怎么办?

2 个答案:

答案 0 :(得分:3)

请检查我已使用您的代码更新的输出。这就是你想要的,只有我做过的事情,我已经将所有内容包装在div中并迭代每个图像以替换其alt属性。

    $("#mycontent img").each(function () {
        var altText = $(this).attr("alt");
        $(this).replaceWith(altText);
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="mycontent">
    Hello this is long content with multiple images
    <img alt=":*" src="kissing_heart.png"> and smiley is <img alt=":D" src="smiley.png">.
</div>

答案 1 :(得分:1)

jQuery解决方案,正如要求的那样。

$("img").each(function() {
  var altText = $(this).attr("alt");
  $(this).replaceWith(altText);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hello this is long content with multiple images
<img alt=":*" src="kissing_heart.png"> and smiley is <img alt=":D" src="smiley.png">.