更改 HTML 个标签,包括相同标签的子标签

Change HTML tags, including children of same tag

我正在使用此 previously answered question 来更改 HTML 标签,并且在尝试更新某些 HTML 标签时,我无法访问相同的标签。

例如,将跨度更新为 div 应导致:

<div>
    <div>div within a div</div>
</div>

但显示如下:

<div>
    <span>div within a div</span>
</div>

作为参考,这是 js:

var divTag = 'div';

$('span').each(function() {
    var outer = this.outerHTML;

    // Replace all span tags with the type of divTag
    var regex = new RegExp('<' + this.tagName, 'i');
    var newTag = outer.replace(regex, '<' + divTag);

    // Replace closing tag
    regex = new RegExp('</' + this.tagName + '>$', 'i');
    newTag = newTag.replace(regex, '</' + divTag + '>');

    $(this).replaceWith(newTag);
});

非常感谢任何帮助!谢谢!

var div = $("div");
var html = div[0].outerHTML.replace(/div(?=>)/gi, "span");
console.log(html);
div.replaceWith(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>
    <div>div within a div</div>
</div>

对@guest271314的解决方案稍作改造,避免替换内容,只替换HTML标签。

var div = $("div");
var html = div[0].outerHTML.replace(/<div/g, "<span");
div.replaceWith(html);

FIDDLE: https://jsfiddle.net/lmgonzalves/31c5bebx/1/

编辑:

$("div").each(function(){
    var html = $(this)[0].outerHTML.replace(/<div/g, "<span");
    $(this).replaceWith(html);
});

FIDDLE: https://jsfiddle.net/lmgonzalves/31c5bebx/5/