Javascript - 清理特定的 html 元素



首先,我以 html 的形式从 API 返回。这将在我的jqgrid中使用。示例返回将是这样的我的对象的示例名称是 obj 。那么obj.something下面是。

<div title="custom_title">
    <div id="upper">
         data from somewhere and this is the part that sometimes need to be sanitized without affecting the other tags
    </div>
</div>

到目前为止,我尝试的是尝试这样做: var esc = $(''); 然后确实这样做了:esc.text(obj.something).html();但它会净化所有这些。关于如何纯粹在 javascript 上进行清理,我可能不知道什么吗?

任何帮助将不胜感激。

在这种情况下,您可以使用 DOMPurify

DOMPurify清理HTML并防止XSS攻击。你可以用充满脏HTML的字符串来输入DOMPurify,它将返回一个带有干净HTML的字符串。DOMPurify将删除所有包含危险HTML的内容,从而防止XSS攻击和其他肮脏的内容。

在这里同意@Juhana的观点:"返回包装在 HTML 中的未经净化的输出确实是您应该避免的。但是,如果没有,并且您想控制和清理 DOM,您可以在普通 JS 中执行此操作:

obj = {};
obj.something = '<div title="custom_title"><div id="upper">data from somewhere and this is the part that sometimes need to be sanitized without affecting the other tags</div></div>';
         
var container = document.createElement("div"); //create an element in memory
container.insertAdjacentHTML('afterbegin', obj.something); //serialize the HTML string into the structure.
   container.querySelector("#upper").innerHTML = ""; //empty the element, removing the data in it. (or do something else with it, like stripping all the a elements that do not start with http(s).
console.log(container)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

它将 HTML obj 渲染成内存元素,然后您可以对其执行 DOM 操作并删除 id upperdiv 的内容。完成后,将容器div 的内容插入网格中。

最新更新