使用javascript在h5中添加一个span标签

Add a span tag inside a h5 using javascript

本文关键字:一个 span 标签 javascript h5 添加 使用      更新时间:2023-09-26

我想在这个h5标签内插入一个类的span,这将适用于第一个单词:

<div class="container_skitter" style="width: 715px; height: 230px;">
   <div class="image">
      <a href="#">
      <div class="label_skitter" style="width: 715px; display: block;">
        <h5>Increase knife life</h5>
      </div>
   </div>
</div>

<div class="container_skitter" style="width: 715px; height: 230px;">
   <div class="image">
      <a href="#">
      <div class="label_skitter" style="width: 715px; display: block;">
        <h5><span class="firstword">Increase</span> knife life</h5>
      </div>
   </div>
</div>

是这样的吗?

<script>
    $('h5').html(function (i, html) {
    return html.replace(/('w+'s'w+)/, '<span>$1</span>')
});
</script>

似乎不能使它工作。

谢谢

添加到document.ready下。在完全加载DOM之前,脚本运行得太早了。此外,您只需要匹配第一个单词,因此这足以选择它。/('w+'s)/

$(document).ready(function(){
     $('h5').html(function (i, html) {
     return html.replace(/('w+'s)/, '<span class="test">$1</span>')
     });
   });

小提琴

你做对了。让我们尝试在没有JQuery的情况下做到这一点!

<script>
    Array.prototype.slice.call (document.querySelectorAll ('h5')).forEach
      function (h5el) {
        // we will come here with h5el referencing an h5 of the document
        h5el.innerHTML = h5el.innerHTML.replace (/^('w+)'s/, 
          '<span class="firstword">$1</span> ';
      });
</script>

将这个脚本放在标签的前面或后面,然后,所有的h5元素都将被修改。