`

javascript - trick to getText and setText

阅读更多

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>
 
分享到:
评论

相关推荐

    python-trick

    Python-trick,上传的事pdf文档

    S-a-D-trick.rar_Join In

    split file and join write in vb6

    深度学习领域CNN橄榄球比赛NFL目标检测(带数据集)-cnn-baseline-more-tta-trick

    语言:python 内容包括:源码、数据集、数据集描述、论文 目的:使用CNN算法在橄榄球比赛中目标检测。 带数据集很好运行,主页有搭建环境过程。主页有更多源码。 数据集描述如下: 在这场比赛中,你的任务是预测球员...

    tips-n-trick

    概述 这是Tips-N-Trick,书签等面向公众的文档。

    gtg-grind-trick-generator

    gtg-grind-trick-generator PWA Web应用程序(Node.js,JS,HTML,CSS) Chrome,Safari,Firefox,Edge(Android,iOS,MacOS,Windows) 离线工作Android应用程式使用Google Workbox,Webpack制作

    chinese-nlp-ner-master_chinese_BLSTM_

    一套针对中文实体识别的BLSTM-CRF解决方案,主要包括:数据处理,模型构建,模型训练,模型测试,服务部署(thrift和flask)两种方式。

    py-trick-book:关于 Python 的高级提示和技巧

    Python 提示和技巧 ... git clone https://github.com/plasmashadow/py-trick-book.git 我假设您安装了 ipython 导航到目录并执行 ipython notebook 笔记: 退出间谍活动并自己阅读 或者 保持冷静,加入草帽海贼团

    21-card-trick:在 React 中完成的 21 张卡片技巧

    React 21 卡技巧一个演示卡片技巧的React应用程序。动机该项目旨在学习如何使用 React 钩子和进行嵌套的 api 调用。 该项目不再进行。怎么玩记住 21 张卡片中的 1 张后,单击完成。 选择您的卡片所在的 3 堆中的哪一...

    HLP-Trick-crx插件

    语言:English (United States) 该扩展程序重新启用了网页上的复制/粘贴功能,上下文菜单和本机突出显示功能。

    CMCC-Trick:招惹CMCC-* WLAN

    Trick-CMCC 利用CMCC公共热点的小漏洞免费上网~~ :) sudo ./conn.sh Notice: 目前只知道我工CMCC有这特色, 其他地区尚不明确 Notice: 脚本适用于使用NetWorkManager网络sds管理工具的系统 Notice: 不必惊讶原理, ...

    HLP-绝招「HLP-Trick」-crx插件

    该扩展程序重新启用网页上的复制/粘贴功能,上下文菜单和本机突出显示功能。 支持语言:English (United States)

    [Head.First.JavaScript].Michael.Morrison...

    specialist, you’ll be able to take a cluttered room of JavaScript data and impose your will on it with a flurry of virtual labels and storage bins. storing data Your scripts can store data 34 Scripts...

    Trick

    Trick

    NIO trick and trap NIO网络

    NIO trick and trap NIO,编写高性能Java NIO网络框架

    css-skill.zip

    css-trick css常用的开发技巧

    The Kernel Trick.pdf

    机器学习中为什么需要 Kernel Trick 以及 Kernel Trick 的证明。

    vdr-hattrick-开源

    vdr-hattrick是视频磁盘录像机(VDR)的插件。 它显示了在线足球游戏“ hattrick”(http://www.hattrick.org/)提供的实时比赛。

    snd-reversingwithlena-tutorials-qq664849305.rar

    10. Continued reversing techniques in VB, use of decompilers and a basic anti-anti-trick 11. Intermediate patching using Olly's "pane window" 12. Guiding a program by multiple patching. 13. The use ...

    计算机网络第六版答案

    28. Trudy can pretend to be Bob to Alice (and vice-versa) and partially or completely modify the message(s) being sent from Bob to Alice. For example, she can easily change the phrase “Alice, I owe ...

    Hattrick球场上座率概算

    Hattrick球场上座率概算 Hattrick球场上座率概算

Global site tag (gtag.js) - Google Analytics