[英]Javascript - Getting formatted textContent of an element?
假设我有以下 div:
<div id="some-div">
<div id="sub-div">Lorem <b>ipsum</b> dolor <a href="https://www.example.com/">sit</a> amet, consectetur adipisici elit</div>
</div>
现在,当我得到这个 div 的 textContent 时,我得到Lorem ipsum dolor sit amet, consectetur adipisici elit
。 我想要的是Lorem <b>ipsum</b> dolor sit amet, consectetur adipisici elit
(它也可以是<b>
以外的其他标识符,表示“ipsum”是粗体)。
我不想要像<a>
-Link 这样的东西(因为那只是sub-div
的innerHTML
)。
这些方面的东西可能有用吗?
将您想要的标签转换为非 html 标记(如 bb 代码)
阅读 innerText 以删除所有其他 html 标记
将 bb 代码转换回 html
更新
按“CLICK”文本,结果将打印到控制台
function replaceTag(node, tag) { let tags = node.querySelectorAll(tag) tags.forEach( (item) => { item.outerHTML = `[${tag}]${item.innerHTML}[/${tag}]` }) } function ex() { // create a clone to mutate let node = document.getElementById("targetNode").cloneNode(true) // list of desired tags let tags = ["b", "i", "u", "s"] // replace tags with bb code style markup tags.forEach ( (tag) => { replaceTag(node,tag) }) // print the innerText to console (replacing bb code with html) console.log(node.innerText.replace(/\[([bius])\](.+?)\[\/\1\]/g,'<$1>$2</$1>')) }
<div id="targetNode"><span>Span</span><b>BOLD</b><i>italic</i><s>strike</s></div> <div onclick="ex()">CLICK</div>
更新
没有经过全面测试,给定一个节点和所需标签列表,它应该返回类似 innerText 的内容,并保留所需的标签(尽管它不会保留与它们关联的任何属性)
function getFilteredHTML(targetNode, tags = ["b", "i", "u", "s"]) {
let node = targetNode.cloneNode(true)
let expr = new RegExp("\\[("+tags.join("|")+")\\](.+?)\\[\\/\\1\\]","g")
tags.forEach( (tag) => {
let searchTag = node.querySelectorAll(tag)
searchTag.forEach( (item) => { item.outerHTML = `[${tag}]${item.innerHTML}[/${tag}]` } )
})
return node.innerText.replace(expr,'<$1>$2</$1>')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.