javascript - trick to getText and setText

本文深入探讨了在JavaScript中操纵元素文本的复杂性,通过代码示例展示了如何使用`setText`和`getText`函数实现元素文本的设置和获取,特别关注了包含子元素的情况,并提供了测试代码验证功能。

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

it is not as simple as you think to settext or get text to some element in javascript, by simply reading the textContent or write to the text content. 

 

 

 

Below show the code on the impl of getText and setText, along with its imple comments.

 

 

/**************************************
*@Name: textcontent.js
*@Summary
*  This example will shows you some technique to manipulate the text inside the 
*
* 
* set text to some element, we have to consider the situation when the element has child elements (including the text child elements) 
* 
* and get text, we have to go through the text to find one . 
*
***************************************/


/**
* @Function: setText
* @Summary: setText
* @Comment: You will need to remove the original child element so that you will have a clean elemnet to insert text to
*
* NOTE: this code shows example, and is not supposed to be useful without context.
*/
function setText(elem, text) {
  while (elem.firstChild) {
    elem.removeChild(elem.firstChild);
  }

  // inject the escaped text node; 
  // NOTE: please do not insert the text just as simply as you think 
  elem.appendChild(document.createTextNode(text));

}

/**
* @Function: getText
* @Summary: getText
* @Comment: you will need to iterate through the elem's children.
*
* NOTE: this code shows example, and is not supposed to be useful without context.
*/
function getText(elem) {
  var text = "";

  for (var i = 0, l = elem.childNodes.length; i < l; i++) {

    var cur = elem.childNodes[i];
    // A text node has a nodeType === 3
    if (cur.nodeType === 3)
      text += cur.nodeValue;
    // If it's an element we need to recurse further
    else if (cur.nodeType === 1)
      text += getText(cur);
  }
  return text;
}

 

and below is the test code that shows you how to use the function .

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- textcontent.html -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="../unit.js"></script>
    <script type="text/javascript" src="textcontent.js"></script>
    <script type="text/javascript">
      window.onload = function () {
        test("test get text", function () {
          var b = document.getElementById("test");
          var text = getText(b);
          assert(text === "Hello, I'm a ninja!", "Examine the text contents of an element.");
          assert(b.childNodes.length === 2, "An element and a text node exist.");
        });

        test("test set text", function () {
          var b = document.getElementById("test");
          setText(b, "Some new text");
          var text = b.textContent || b.innerText;
          assert(text === "Some new text", "Set a new text value.");
          assert(b.childNodes.length === 1, "Only one text nodes exists now.");
        });
      };
    </script>
    <style type="text/css">
      #results li.pass { color:Green }
      #results li.fail { color:red}
    </style>
</head>
<body>
<div id="test"><b>Hello</b>, I'm a ninja!</div>
<div id="test2"></div>
<ul id="results" />

</body>
</html>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值