如何获取父元素HTML内容且排除子元素自身的外层标签?
实现方案
核心思路
遍历父元素下的所有子节点,文本节点直接保留内容,元素节点跳过自身的标签及属性,只拼接内部的内容,需要保留特定标签(比如<br>)时可以加判断条件递归处理嵌套节点。
适配需求的最简实现(基于jQuery)
你提到了jQuery的text()和html()不符合要求,可以用下面的自定义方法实现:
function getCustomHtml($parent) { let res = '' $parent.contents().each(function() { // 文本节点直接拼接 if (this.nodeType === 3) return res += this.textContent.trim() + ' ' // 元素节点取内部html,跳过自身标签属性 res += $(this).html().trim() + ' ' }) return res.trim() } // 调用示例 console.log(getCustomHtml($('.test')))
仅保留<br>标签、清除其余所有元素标签的实现
如果要得到你示例里最终期望的输出,连嵌套的<span>、<i>这类标签也去掉,只保留<br>,可以用递归方案:
function getContentOnlyKeepBr(dom) { let res = '' for (const node of dom.childNodes) { if (node.nodeType === 3) { res += node.textContent } else if (node.tagName.toLowerCase() === 'br') { res += '<br>' } else { res += getContentOnlyKeepBr(node) } } // 替换多余空白符,也可以根据需求去掉这行 return res.replace(/\s+/g, ' ').trim() } // 原生JS调用 console.log(getContentOnlyKeepBr(document.querySelector('.test'))) // jQuery调用 console.log(getContentOnlyKeepBr($('.test')[0]))
运行上述代码就能得到你要的输出结果:
This is content of div This is paragraph<br> content.As you can see I have added <br> tag
内容的提问来源于stack exchange,提问作者Tarunpreet Singh
相关产品推荐
相关产品推荐

