使用jQuery在div中查找替换字符串

时间:2019-06-25 07:03:19

标签: javascript jquery html string

我正在尝试在div标签内找到嵌套的字符串,并将字符串替换为jQuery

$( ".short-features col-sm-4.inner" ).replaceWith( "<strong>Engine</strong> :</span> Manual</div>" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="short-features">
  <!-- Heading Area -->
  <div class="heading-panel">
    <h3 class="main-title text-left">Details</h3>
  </div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding">
  </div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding">
    <span><strong>Engine</strong> :</span> Automatic
  </div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding"></div>
</div>

它不起作用,我在做错什么吗?

2 个答案:

答案 0 :(得分:0)

请注意,没有element类的inner

您还缺少.中的jquery

$(".short-features .col-sm-4.inner").replaceWith("<strong>Engine</strong> :</span> Manual</div>");
                   ^
                   was missing

演示

$(".short-features .col-sm-4.inner").replaceWith("<strong>Engine</strong> :</span> Manual</div>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="short-features">
  <!-- Heading Area -->
  <div class="heading-panel">
    <h3 class="main-title text-left">
      Details </h3>
  </div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding"></div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding inner"><span><strong>Engine</strong> :</span> Automatic</div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding"></div>
</div>

答案 1 :(得分:0)

由于类element中没有inner,因此您需要检查div是否具有跨度?如果是,则将其替换为新数据

$( ".short-features .col-md-4" ).has('span').replaceWith( "<strong>Engine</strong> :</span> Manual</div>" );

//------------------^ forgot .---^check span--^then replace ---------------//

工作片段

$( ".short-features .col-md-4" ).has('span').replaceWith( "<strong>Engine</strong> :</span> Manual</div>" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="short-features">
  <!-- Heading Area -->
  <div class="heading-panel">
    <h3 class="main-title text-left">Details</h3>
  </div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding">
  </div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding">
    <span><strong>Engine</strong> :</span> Automatic
  </div>
  <div class="col-sm-4 col-md-4 col-xs-12 no-padding"></div>
</div>

注意:-或您可以 将类inner添加到其中包含<span>的div中,然后您可以直接进行以下操作:< / p>

$( ".short-features .col-md-4.inner" ).replaceWith( "<strong>Engine</strong> :</span> Manual</div>" );

您在评论中要求使用的:contains() Selector

$( ".short-features .col-md-4" ).has("span:contains('Engine')").replaceWith( "<strong>Engine</strong> :</span> Manual</div>" );

工作链接:-https://jsfiddle.net/n37q169f/