找到img标签并替换为另一个标签

时间:2015-07-02 07:27:37

标签: jquery image replace src

如何找到img标记并使用jQuery将其替换为span标记?

<style>
    .box{
      display:inline-block;
      width:100px;
      height:20px;
      line-height:20px;
      font-size:11px;
    }
</style>

<p id="recommend">
    <img src="search.gif" alt="find"> <!-- find this img tag without id and class-->
</p>

<!-- next -->

<p id="recommend">
    <span class="box">search</span><!-- replace this -->
</p>

3 个答案:

答案 0 :(得分:0)

您可以使用jquery的replace()replaceWith()方法来实现您的目标。

以下是其用法的链接:

https://api.jquery.com/category/manipulation/dom-replacement/

http://api.jquery.com/replacewith/

答案 1 :(得分:0)

<style>
.box{display:inline-block;width:100px;height:20px;line-height:20px;font-size:11px;}
</style>

<p id="recommend">
    <img src="search.gif" class="find"> <!-- find this img tag without id and class-->
</p>

<script type="text/javascript">
$(document).ready(function() {
    $('<span class="box">search</span>').replaceAll('img.find');
    // OR...
    $('img.find').replaceWith('<span class="box">search</span>');
});
</script>

https://api.jquery.com/replaceAll/

http://api.jquery.com/replacewith/

答案 2 :(得分:0)

正如其他人所说,身份证应该是独一无二的。相反,您可以使用class为多个元素共享相同的类名。在这里,我举一个例子来实现:

<强> HTML

<p class="recommend">
   <img src="search.gif" alt="find" />
   <!-- find this img tag without id and class-->
</p>
<!-- next -->
<p class="recommend">
<span class="box">search</span>
 <!-- replace this -->
</p>

<强>的jQuery

$('.recommend').first().find('img').remove().end().html(function(){
    return $(this).siblings().find('span.box');
});

$('img').replaceWith(function(){
 return $(this).parent().next().find('span.box');
});

如果要将图像替换为span的内容,请添加.html()

DEMO - 检查元素以查看替换内容。

相关问题