DOM操作是前端必须掌握的技能之一, 而最经常做的就是读取和修改元素节点的文本内容,这里给大家列出7种获取/修改文本内容的方式, 供大家参考!
通过直接修改文本节点 节点一共具有三个属性, nodeType, nodeValue, nodeName 只有注释, 文本, 属性具备nodeValue 所以我们可以直接获取目标节点的子文本节点
target.firstChild.nodeValue //需要保证第一个子节点是文本节点 target.childNodes[0].nodeValue //同理很明显, 仅仅适用于 文本节点是直接子节点 的 元素节点
利用textContent 这是DOM3新增的方法, 使用前务必先做判断, IE8及更早版本不兼容 可以使用innerText做兼容, 效果类似, 不过适用更广(ps: 何不用innerHTML)
let text = target.textContent || target.innerText最后一种, 也是适用性最广的方法 操作节点的 innerHTML 属性
let text = target.innerHTML那么innerHTML就一定好吗? 也并不是, innerHTML进行大量运算的时候会造成严重的性能问题 以下是我搜集到的解决方案 https://www.cnblogs.com/firstdream/p/5530029.html https://www.cnblogs.com/wangdan0915/p/8136332.html
function replaceHtml(el, html) { var oldEl = typeof el === "string" ? document.getElementById(el) : el; /*@cc_on // Pure innerHTML is slightly faster in IE oldEl.innerHTML = html; return oldEl; @*/ var newEl = oldEl.cloneNode(false); newEl.innerHTML = html; oldEl.parentNode.replaceChild(newEl, oldEl); /* Since we just removed the old element from the DOM, return a reference to the new element, which can be used to restore variable references. */ return newEl;};
作为扩展这里介绍下 还有存在三种类似属性 outerHTML 返回标签和内容组成的字符串 innerText 获取从始至终所有文本内容(**不含HTML标签**) outerText 获取元素自身, 不含子元素文本内容 **但是在红宝书最新版中指出, 尽量只是用innerHTML**