简体   繁体   English

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

[英]Change HTML tags, including children of same tag

I'm using this previously answered question about altering an HTML tag and while trying to update some HTML tags, I'm having trouble reaching the tags within a parent of the same tag. 我正在使用有关更改HTML标签的先前回答的问题 ,并且尝试更新一些HTML标签时,无法在同一标签的父级中到达这些标签。

For example, updating a span to a div should result in: 例如,将范围更新为div应该导致:

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

But is showing up like: 但显示如下:

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

And for reference, this is the js: 供参考,这是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);
});

Any help is greatly appreciated! 任何帮助是极大的赞赏! Thanks! 谢谢!

A little transformation in @guest271314 solution, to avoid replace the content, only replace the HTML tags. @ guest271314解决方案中的一些转换,避免替换内容,仅替换HTML标记。

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

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

EDIT: 编辑:

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

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

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM