normalize、splitText

本文详细介绍了DOM操作中的normalize方法与splitText方法。normalize方法可以将一个父元素内的多个文本节点合并为一个,而splitText方法则用于将一个文本节点分割成两个。通过具体的JavaScript代码示例,展示了如何使用这两种方法来更好地管理和操作DOM中的文本内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、normalize:如果在包含两个或者多个文本节点的父元素上调用normalize()方法,则会将所有文本节点合并成一个节点;
var oDiv = document.createElement("div");
    var text1 = document.createTextNode("第一个");
    oDiv.appendChild(text1);
    var text2 = document.createTextNode("第二个");
    oDiv.appendChild(text2);
    document.body.appendChild(oDiv);
console.log(oDiv.firstChild.nodeValue);  //得到:第一个;

如果调用normalize();
var oDiv = document.createElement("div");
    var text1 = document.createTextNode("第一个");
    oDiv.appendChild(text1);
    var text2 = document.createTextNode("第二个");
    oDiv.appendChild(text2);
    document.body.appendChild(oDiv);

oDiv.normalize()
console.log(oDiv.firstChild.nodeValue); //返回  第一个第二个;合并成了一个文本节点;
2、splitText():分割文本节点;与normalize正好相反;
    var oDiv = document.createElement("div");
    var text1 = document.createTextNode("第一个和第二个文本节点");
    oDiv.appendChild(text1);
    document.body.appendChild(oDiv);
    oDiv.firstChild.splitText(5);
    console.log(oDiv.firstChild.nodeValue);//返回:“第一个和第”  从splitTextu括号中的数字5开始分割的;
    console.log(oDiv.lastChild.nodeValue); //返回:“二个文本节点”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值