我想使用我的HTMLCollection去掉它包含的元素的标签,例如,给定html:
<p><span>Hello, <i>world!</i></span> Some more text</p>
我想返回
<p>Hello, <i>world!</i> Some more text</p>
当我在我的html中搜索span标签时返回一个HTMLCollection,这似乎是我获取所有span标签的最简单方法,我如何使用此集合完全剥离标签并保留所有innerhtml?
$scope.modifyHtml = function (html) {
var el = document.createElement('div');
el.innerHTML = html;
var spans = el.getElementsByTagName('span');
//Remove these spans from el but keep their inner!
return el.innerHTML;
}
答案 0 :(得分:2)
自标记为jQuery
$scope.modifyHtml = function (html) {
var $tmp = $('<div />', {
html: html
});
//remove span elements
$tmp.find('span').contents().unwrap();
return $tmp.html()
}
演示:Fiddle
没有jQuery
$scope.modifyHtml = function (html) {
var el = document.createElement('div'),
spans, span, len;
el.innerHTML = html;
spans = el.getElementsByTagName('span'), span;
for (var i = 0; i < spans.length; i++) {
span = spans[i];
len = span.childNodes.length;
for (var j = 0; j < len; j++) {
span.parentNode.insertBefore(span.childNodes[0], span)
}
span.parentNode.removeChild(span);
}
return el.innerHTML;
}