[英]How can I strip HTML tags that have attribute(s) from string?
我有一个像这样的问答网站。 我也有一个textarea及其下的预览(与SO完全相同) 。 我使用markdown库将一些符号转换为HTML标签。 例如,JS库将**
替换为<b>
。 好的,一切都好。
现在,我需要转义具有属性的HTML标记。 我可以这样用PHP做到这一点 :
<?php
$data = <<<DATA
<div>
<p>These line shall stay</p>
<p class="myclass">Remove this one</p>
<p>But keep this</p>
<div style="color: red">and this</div>
</div>
DATA;
$dom = new DOMDOcument();
$dom->loadHTML($data, LIBXML_HTML_NOIMPLIED);
$xpath = new DOMXPath($dom);
$lines_to_be_removed = $xpath->query("//*[count(@*)>0]");
foreach ($lines_to_be_removed as $line) {
$line->parentNode->removeChild($line);
}
// just to check
echo $dom->saveHtml($dom->documentElement);
?>
我不确定上面的代码是最好的,但是如您所见(在我链接的小提琴中),它可以按预期工作。 我的意思是,它将删除至少一个属性的节点。 现在,我需要通过JS (或jQuery)来做到这一点( 对于textarea预览模拟器 ,我需要这样做) 。 无论如何我该怎么做? 我需要正则表达式吗?
您可以执行以下操作:
$('.myTextArea *').each(function(){
if (this.attributes.length)
$(this).remove();
});
它不是最有效的,但是如果只是文本区域预览,那应该没问题。 我建议尽可能少地运行它。 据我所知,没有选择器(jQuery或其他方式)可以执行此操作...所以您必须让JS来工作。
根据评论进行编辑:
要不删除元素,只需删除周围的标签,请执行以下操作:
$('.myTextArea *').each(function(){
if (this.attributes.length)
this.outerHTML = this.textContent;
});
JavaScript element.attributes
属性返回标签属性及其值的实时NamedNodeMap
。 例如...
的HTML
<div class=".cls" id="id" title="divtitle">
<!-- content ... -->
</div>
的JavaScript
var div = document.getElementById('id');
var attr = div.attributes;
console.log(attr);
/* =>
NamedNodeMap [class="cls", id="id", title="divtitle"]
*/
这可以用来过滤选定的项目-例如您的示例...
/* return an array from querySelectorAll */
var paras = Array.prototype.slice.call(
document.querySelectorAll('div p')
);
/* loop through paras */
paras.forEach(function(p) {
/* 'p' = each element in 'paras' */
/* get attributes of 'p' */
var attr = p.attributes;
/* only check elements with attributes */
if (attr.length != 0) {
/* loop through attributes */
Object.keys(attr).forEach(function(a) {
/* apply conditional */
if (attr[a].name === 'class' && attr[a].value === 'myclass' ||
attr[a].name === 'style' && attr[a].value === 'color: red;') {
/* remove element ('p') */
p.parentElement.removeChild(p);
}
});
}
});
因为NamedNodeMap
是对象的一种类型,所以我使用Object.keys(obj)
返回一个键数组,然后遍历它们以确定属性的.name
和.value
属性。
编辑:鉴于以上评论
如果您只想删除属性,则可以删除上面的条件,就像这样...
paras.forEach(function(p) {
var attr = p.attributes;
if (attr.length != 0) {
Object.keys(attr).forEach(function(a) {
p.removeAttribute(a);
});
}
});
看到:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.