weixin_33676492 2015-07-26 23:56 采纳率: 0%
浏览 137

是TextNode还是textContent?

What's the advantage of creating a TextNode and appending it to an HTML element over setting directly its textContent?

Let's say I have a span.

var span = document.getElementById('my-span');

And I want to change its text. What's the advantage of using :

var my_text = document.createTextNode('Hello!');
span.appendChild(my_text);

over

span.textContent = 'hello';

  • 写回答

1条回答 默认 最新

  • George_Fal 2015-07-27 01:38
    关注

    It 's not really matter of advantage but of proper usage depending on the need.

    The fundamental difference is that:

    • createTextNode() is a method and works just as its name says: it creates an element... then you must do something with it (like in your example, where you append it as a child);
      so it is useful if you want to have a new element and place it somewhere
    • textContent is a property you may get or set, with a unique statement and nothing else;
      so it is useful when you only want to change the content of an already existing element

    Now in the precise case of your question, you said you want to change the text of the element...
    To be more clear say you have the following HTML element:

    <span>Original text</span>
    

    If you're using your first solution:

    var my_text = document.createTextNode('Hello!');
    span.appendChild(my_text);
    

    then it will end with:

    <span>Original textHello!</span>
    

    because you appended your textNode.

    So you should use the second solution.

    评论

报告相同问题?

悬赏问题

  • ¥15 c++的教材订购系统的订购模块显示运行不出来
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值