replaceWith()无法返回标签,如何实现文本截断并包裹标签?
解决replaceWith()包裹文本到HTML标签的问题
咱们先来拆解你遇到的几个核心问题:
newValuare.text()报错:因为newValuare是你拼接出来的字符串,只有DOM元素才有text()方法,字符串压根没这个属性~- 标签以纯文本显示:直接传HTML格式的字符串给
replaceWith()时,它会把整个字符串当作普通文本插入,不会自动解析成HTML元素。
下面给你几种靠谱的实现方案:
方案一:创建DOM元素后替换(推荐)
这种方式更规范,还能避免字符串拼接可能带来的XSS风险:
let content = document.getElementById('videoText'); let valuare = content.innerHTML; let lungime = valuare.length; if (lungime > 40) { let newValuare = valuare.substring(0, 40) + " ..."; console.log(newValuare); // 创建新的span元素 const newSpan = document.createElement('span'); // 给新元素设置文本内容 newSpan.textContent = newValuare; // 用新元素替换掉原元素 content.replaceWith(newSpan); }
方案二:解析HTML字符串为元素再替换
如果你更习惯用HTML字符串的写法,可以借助DOMParser把字符串转换成可识别的DOM节点:
let content = document.getElementById('videoText'); let valuare = content.innerHTML; let lungime = valuare.length; if (lungime > 40) { let newValuare = valuare.substring(0, 40) + " ..."; console.log(newValuare); // 把HTML字符串解析成DOM片段 const parser = new DOMParser(); const newSpan = parser.parseFromString(`<span>${newValuare}</span>`, 'text/html').body.firstChild; // 执行替换操作 content.replaceWith(newSpan); }
方案三:直接修改原元素内容(无需replaceWith)
其实你也可以不用替换整个元素,直接修改原videoText的内容就行,步骤更简单:
let content = document.getElementById('videoText'); let valuare = content.innerHTML; let lungime = valuare.length; if (lungime > 40) { let newValuare = valuare.substring(0, 40) + " ..."; console.log(newValuare); // 直接覆盖原元素的内容 content.innerHTML = newValuare; }
小补充
- 如果你需要保留原元素的
id或者其他属性,方案三更合适,因为它只是修改内容,不会替换掉原元素本身。 - 方案一和方案二更适合需要完全替换成新元素的场景。
内容的提问来源于stack exchange,提问作者Neagu Claudiu Alexandru
相关产品推荐
相关产品推荐

