怎么把dom元素的文本中的数字先取出来然后再改变数字颜色

问题描述

一段文本例如“我的123联发科456浮夸789”,把123456789取出来组成数组或者其他的数据类型,然后把123456789改变颜色,再放回去,这个功能能否实现?

阅读 3.2k
4 个回答

HTML

<p id="demo">
  我的123联发科456浮夸789
<p>

STYLE

<style type="text/css">
    #demo span {
        color: red;
    }
</style>

JS

let text = document.getElementById("demo").innerText;
let html = text.replace(/(\d+)/g, `<span>$1</span>`);
document.getElementById("demo").innerHTML = html;

正则的字符串替代~ 数字加个标签 <span style="color:red;">123</span>

正则不精通,不过也实现了:

        <style>
        .onlyone{
            color: red;
        }
    </style>
    <div id="div">
        我的123联发科456浮夸789
    </div>
    
    <script>
        var ins = document.getElementById('div');
        var arr = ins.innerText.match(/\d{1,}/g);
        ins.innerHTML = ins.innerText.replace(/\d{1,}/g,'<span class="onlyone"></span>')
        var el = document.querySelectorAll('.onlyone');
        el.forEach(function(item,i){
            item.innerText = arr[i]
        })
    </script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题